g.pickardou g.pickardou - 9 months ago 34
Javascript Question

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


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
// My conditional code here


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...



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.


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.