What does ==, ===, false, undefined and nan mean in Javascript?
Comparison via ==
== indicates Equality, regardless of type.
Comparison via ===
=== indicates identity, types must match.
Pitfalls using comparison
For boolean operations it evaluates to false. Use === when comparing to the number 0.
var x = 0;
var y = false;
x == y → true
x === y → false
"" (empty string)
Evaluates to false in boolean operations. Use === when comparing to an empty string.
var x = "";
var y = false;
x == y → true
x === y → false
null
Evaluates to false in boolean operations. Use === when comparing to null.
var x = null;
var y = false;
x == y → true
x === y → false
undefined
If a variable hasn't been declared or assigned yet (e.g: an argument to a function which never received a value, an object property that hasn't been assigned a value) then that variable will be given a special undefined value.
Evaluates to false in boolean operations. Always use === when comparing to undefined.
var x;
var y = false;
typeof(x) → undefined (as a string)
x == y → true
x === y → false
NaN
Not a Number, generated when arithmetic operations return invalid results.
Evaluates to false in boolean operations. Always use isNaN() when comparing to NaN.
var x = 10/seventeen;
x → NaN
NOTE: NaN is never equal to itself!
var x = 10/seventeen;
x == x → false
Courtesy: http://www.hunlock.com/blogs/Essential_Javascript_--_A_Javascript_Tutorial
This is a very good JavaScript site. Many of my misconceptions were cleared when I went thru this site.
Hope these concepts help you!
Monday, March 9, 2009
JavaScript Fundas: null, undefined, nan, false
Posted by Sandeep Aparajit at 10:25 AM
Labels: Javascript
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment