Search code examples
javascriptoperators

Why does value of a variable change inside if statement


Look at this small snippet of JS:

var a = 1;

if(! (--a)) { // when I say --a I didn't mean to say "change the value of a" i just meant to say "without manipulating the actual value of a, just check if --a is falsy"
  console.log('ok');
}

console.log(a); // 0 ... Why? I never intended to change the value of a 

Why is it that when I am not explicitly setting the value of a to be --a is the value of a being manipulated? In the if condition I really didn't mean to say that actually reduce the value of a, it was just an "if check" I thought would change the value of a.

Well I am obviously wrong I guess. I just wanted to know, is this just a JavaScript thing or is this common to all programming languages ? (I.E. being able to manipulate the value of a variable in an if condition, when actually all you want to do is temporarily manipulate the value of the variable and not change the actual value).

Edit

I wasn't asking to explain how a-- and --a works, I want to know why does:

PROGRAMME ONE:

var a = 1;

--a;

console.log(a) // my expected output is 0

PROGRAMME TWO:

var a = 1;

if(--a){};

console.log(a) // my expected output is still 1 , because I didn't expect --a inside the if to actually manipulate a. 

so basically my question is why does --a work inside the if and not HOW does --a work !


Solution

  • if is not only a conditional statement but also executes code written in it i.e the condition is evaluated

    eg 1:

    if(a == 5) {} //checking value of a
    

    but

    if(a = 5) //assigning 5 to a but also checking value of a as Undefined, null
    

    eg 2:

    Similarly in a for...loop

    for(var i=0; i<10; i++)
    

    initiation, condition check and updation of value altogether gets performed

    In your case --a will also act as a code statement and after that it will act as a conditional statement which will get executed and will return a value of 0 means you variable will get changed and ! will negate it and will make it true(though it does not matter what you are asking).

    if(! (--a)) { // when i say --a i did't mean to say "change the value of a" i just meant to say "without manupulating the actual value of a , just check if --a is falsy"
      console.log('ok');
    }
    
    console.log(a);