Saturday, June 11, 2011

Javascript: How Double And "&&" Works

Recently this question baffled us all.Coming from other languages we would expect that following line

var result =  true && "Rizwan" ;

assigns true or false to result variable (true in above case) but if you do "alert(result)" in next line , you see "Rizwan" in the alertbox instead of true.Confused? Read till end and it will be clear.

Javascript and Falsy Values

    In javascript following are considered false

  •    false
  •    0
  •    null
  •    undefined
  •    "" ,empty String
  •    NaN (Not a number , like 0/0)


Everything else evaluates to true.

Keeping this in mind , we go back to our problem

var result =  true && "Rizwan";

In javascript && operator evaluates its first operand and if its true, it returns whatever is the second operand ("Rizwan" in the above case) .

And if first operand is falsy value , && operarot just returns that first operand.

var result =  null && "Rizwan"; // result will contain null

Similary || operator returns its first operand if its true , otherwise it returns it second operator if first operator is a falsy value.