JavaScript pitfalls: null, false, undefined, NaN

From MapbenderWiki

Jump to: navigation, search

Contents

Comparison operators

Comparison via ==

Equality, regardless of type.

Comparison via ===

Identity, types must match. Always use this syntax, if possible.

Pitfalls using comparison

0

Evaluates to false in boolean operations. Always 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. Always 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. Always 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 (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

Source

see http://www.hunlock.com/blogs/Essential_Javascript_--_A_Javascript_Tutorial

In general a very good and interesting site, yet some of their examples contradict to my judgment of good code, so beware.

Views
Personal tools