if

The if statement is the fundamental control statement that allows JavaScript to make decisions, or, more precisely, to execute statements conditionally. This statement has two forms. The first is:

if (expression)
    statement

In this form, expression is evaluated. If the resulting value is true or can be converted to true, statement is executed. If expression is false or converts to false, statement is not executed. For example:

if (username == null)       // If username is null or undefined,
    username = "John Doe";  // define it

Or similarly:

// If username is null, undefined, 0, "", or NaN, it converts to false, 
// and this statement will assign a new value to it.
if (!username) username = "John Doe";

Although they look extraneous, the parentheses around the expression are a required part of the syntax for the if statement.

As mentioned in the previous section, we can always replace a single statement with a statement block. So the if statement might also look like this:

if ((address == null) || (address == "")) {
    address = "undefined";
    alert("Please specify a mailing address.");
}

The indentation used in these examples is not mandatory. Extra spaces and tabs are ignored in JavaScript, and since we used semicolons after all the primitive statements, these examples could have been written all on one line. Using line breaks and indentation as shown here, however, makes the code easier to read and understand.

The second form of the if statement introduces an else clause that is executed ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.