Flow Control
Prev Chapter 8. JavaScript Basics Next

Flow Control

Flow control lets you run a block of code under certain conditions. You should always use braces to mark the start and end of logical blocks.[1]

Example 8.12. Flow control

var foo = true;
var bar = false;

if (foo) {
    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
}

Truthy and Falsy Things

In order to

Example 8.13. Values that evaluate to true

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

Example 8.14. Values that evaluate to false

0;
'';  // an empty string
NaN; // JavaScript's "not-a-number" variable
null;
undefined;  // be careful -- undefined can be redefined!



[1] Strictly speaking, braces aren't required around single-line if statements, but using them consistently, even when they aren't strictly required, makes for vastly more readable code.


Prev Up Next
Operators Home Loops