Pitfalls

typeof

typeof [] // "object"
typeof null // "object"
typeof NaN // "number"

Type of null is a longstanding bug in JS. Always use the variableName !== null to check if something is not null. Arrays are a sub-type of object. Use Array.isArray to check if an object is an array. Use Number.isNaN(value) to check if a value is NaN.

Falsy values

0 == false //true
'' == false // true
' ' == false // true
'0' == false // true
'false' == false // false
undefined == false // false
null == false // false
null == undefined // true
NaN == NaN // false
" \t\r\n" == false // true

Be careful with conditionals on what will be coerced. 0, "", " ", "0", and "\n" will be coerced. So:

var bar = '0';

if (bar) {
    console.log("doesn't get called");
} else {
    console.log("get's called"); // <--this here 
}

Shorthand variable declaration

var a = b = 3;

// this is shorthand for the following:
b = 3;
var a = b;

Strict mode will generate a runtime error (global variable are disallowed). Outside of strict mode, b will be defined in the global scope.

Floating point precision

console.log(0.1 + 0.2); // 0.30000000000000004

Always round the results of a float calculation.

results matching ""

    No results matching ""