Monday, October 08, 2012

Few observations with Boolean, NULL and NaN in JavaScript

Boolean is the one of primitive data type in the JavaScript. Below are the some observations while working with the Boolean.

// scenario one
var myBool = true;
alert(typeof myBool);//boolean
alert(myBool instanceof Boolean)// false

//scenario two
var myBool = new Boolean(false);

alert(myBool);
alert(myBool instanceof Boolean);//true

//numerics as Boolean
var myTruthValue = 0;
alert(Boolean(myTruthValue));//false

var myTruthValue = 1;
alert(Boolean(myTruthValue));//true

var myTruthValue = -1;
console.log(Boolean(myTruthValue));//true

when ever you are converting 0 to Boolean it yields false, other than 0 it may be a positive or negative it yields true;

var myTruthValue = 0;
alert(Boolean(myTruthValue));
alert(Boolean(myTruthValue) ==  false);// true


var myTruthValue = 1;
alert(Boolean(myTruthValue));
alert(Boolean(myTruthValue) ==  false);// false

//strings as Boolean
var myBool ="a";
alert(Boolean(myBool));//true
var myBool ="a";
alert(Boolean(myBool));//true

var myBool ="";
alert(Boolean(myBool));//false
alert(Boolean(myBool) == true);// true

Some observations with NULL
var myvar = null;
alert(typeof myvar)//object

//null is an Object?..... try with instanceof
alert(myvar instanceof Object);//false

var myval = null;
alert(myval == null);//true

Some observations with NaN
Nan means not a numeric value.we can check a given variable or value is numeric or not...for that we can use isNaN(value).. 

var myval = NaN;
alert(typeof myval);// Number

//one more surprise, NaN is Number?....
alert(isNaN(myval))//true
alert(isNaN(myval))//true

//NaN and numaric string literal
var myval = "-20";
alert(typeof myval);// string
alert(isNaN(myval))//false
myval = parseInt(myval);
alert(typeof myval);//number
alert(isNaN(myval))//false

//one more observation 
alert (NaN == NaN);//false 

var myvar = NaN;
alert (myvar == NaN);//false

i hope above observation will help you in some situations while coding... happy coding friends....




var myval = NaN;
alert(typeof myval);// Number



var myTruthValue = 1;
alert(Boolean(myTruthValue));//true
var myTruthValue = 1;
alert(Boolean(myTruthValue));//true