Saturday 8 December 2018

How the undefined variable behaves in boolean and numeric context?

'undefined' variable is treated as false in boolean context.

HelloWorld.js
var x;

if(x){
  console.log("x is true");
}else{
  console.log("x is false");
}

var y = true;
if(y){
  console.log("y is true");
}else{
  console.log("y is false");
}

Output
x is false
y is true

undefined leads to NaN in numeric context.

HelloWorld.js
var x;

var y = x + 10;

console.log("Value of y is : " + y);

Output
Value of y is : NaN



Previous                                                 Next                                                 Home

No comments:

Post a Comment