g.pickardou g.pickardou - 7 months ago 23
Javascript Question

What is the exact negation of if(variable) in javascript?

Context:

I often see in javascript programs the following conditional statement:

if (myVariable){
....
}


As I understand do fat it tests against both undefined and null but I an not sure what else, I suppose against boolean false...

Theoretically if I want to write the exact negation I can wrote

if (myVariable){
// dummy empty
}
else{
// My conditional code here
}


Question

What is the exact equivalent of the code above in the following simplest form?

if (<what to write here using myVariable>){
// My conditional code here
}


The answer
if (!myVariable)
seems too obvious, and I am not sure there are no traps here regarding undefined, null behaviours...

Answer

try

if (!Boolean(myVariable))
{  
  //logic when myVariable is not 0, -0, null, undefined, false,  
}

check this spec and this

  1. Let exprValue be ToBoolean(GetValue(exprRef)).

So, conversion of Boolean is the first thing that happens to an expression.

You can apply the same thing to an individual variable as well.

Edit:

To explain the question in comment

how the "!myVariabla" expression is evaluating

It will first coerce the expression into a boolean one as per the table given in spec and then negate it.