Truthy and Falsy Things

In order to use flow control successfully, it’s important to understand which kinds of values are “truthy” and which kinds of values are “falsy.” Sometimes, values that seem like they should evaluate one way actually evaluate another.

Example 2.14: Values that evaluate to true

‘0’;
‘any string’;
[]; // an empty array
{}; // an empty object
1; // any non-zero number

Example 2.15: Values that evaluate to false

0;
”; // an empty string
NaN; // JavaScript’s “not-a-number” variable
null;
undefined; // be careful — undefined can be redefined!

Conditional Code

var foo = true;
var bar = false;

if (bar) {
// this code will never run
console.log(‘hello!’);
}

if (bar) {
// this code won’t run
} else {
if (foo) {
// this code will run
} else {
// this code would run if foo and bar were both false
}
}

Comparison Operators

var foo = 1;
var bar = 0;
var baz = ‘1’;
var bim = 2;

foo == bar; // returns false
foo != bar; // returns true
foo == baz; // returns true; careful!

foo === baz; // returns false
foo !== baz; // returns true
foo === parseInt(baz); // returns true

foo > bim; // returns false
bim > baz; // returns true
foo <= baz; // returns true

Logical Operators

Logical operators allow you to evaluate a series of operands using AND and OR operations.

Example 2.11: Logical AND and OR operators

var foo = 1;
var bar = 0;
var baz = 2;

foo || bar; // returns 1, which is true
bar || foo; // returns 1, which is true

foo && bar; // returns 0, which is false
foo && baz; // returns 2, which is true
baz && foo; // returns 1, which is true

Operations on Numbers & Strings

In JavaScript, numbers and strings will occasionally behave in ways you might not expect.

Example 2.8: Addition vs. concatenation
var foo = 1;
var bar = ‘2’;

console.log(foo + bar); // 12. uh oh

Example 2.9: Forcing a string to act as a number
view sourceprint?
var foo = 1;
var bar = ‘2’;

// coerce the string to a number
console.log(foo + Number(bar));

Example 2.10: Forcing a string to act as a number (using the unary-plus operator)
console.log(foo + +bar);