bool 

Send to Kindle
home » snippets » javascript » bool



True and False values

From: http://www.sitepoint.com/javascript-truthy-falsy/

Always falsy values

Everything else is truthy including "0" (string), etc.

Comparison with ==

From: http://oreilly.com/javascript/excerpts/javascript-good-parts/bad-parts.html

The operators == and != attempt coercion on operands of different types.

For example: ' \t\t ' == false,  yet ' \t\t ' is true in a conditional.

In theory, it is better to use === and !==, which do not attempt coercion.

Expression Bool
'' == '0' false
0 == '' true
0 == '0' true
false == 'false' false
false == '0' true
false == undefined false
false == null false
null == undefined true
' \t\r\n ' == 0 true

Snippets

function test(o, name) {
  console.log("Testing: %s", name);
  console.log((o == false) ? "== false", "!= false");
  console.log((o) ? "is NOT falsey", "is falsey");
}

// null == false ?
test(null, "null");
test('', "''");