Skip to content

Basic IF Statements

An if statement runs a block of code only when a condition holds. JavaScript works out the condition in the brackets, and if the result counts as true, it runs the block in the braces; otherwise it skips it and carries on after the block.

const temperature = 28;
if (temperature > 25) {
console.log('Take some water with you.');
}
console.log('Have a good day.');

This prints:

Take some water with you.
Have a good day.

The keyword is lower case. If with a capital letter is not a keyword, so JavaScript reads If (ok) as a function call and stops at the brace after it with SyntaxError: Unexpected token '{'.

An else block runs when the condition does not hold, so exactly one of the two blocks runs:

const temperature = 12;
if (temperature > 25) {
console.log('Wear a sun hat.');
} else {
console.log('Take a jumper.');
}

This prints:

Take a jumper.

The condition is usually a comparison, written with >, <, >=, <=, === (equal) or !== (not equal). Difference between == and === explains why === is preferred to ==.

The condition does not have to be a boolean. JavaScript converts whatever value it gets to true or false, and only a short list of values convert to false. These are the falsy values, and every other value is truthy:

const values = [false, 0, -0, 0n, '', null, undefined, NaN, 'hello', '0', 'false', 42, [], {}];
console.log(values.filter((value) => !value));
console.log(values.filter((value) => value));

This prints:

[ false, 0, -0, 0n, '', null, undefined, NaN ]
[ 'hello', '0', 'false', 42, [], {} ]

The strings '0' and 'false' are truthy, because they are non-empty strings, and so are an empty array and an empty object.

Truthiness gives a short way to test whether something is there:

const todos = [];
if (todos.length) {
console.log(`You have ${todos.length} things to do.`);
} else {
console.log('Nothing left to do.');
}

This prints:

Nothing left to do.

todos.length is 0 for an empty list, which is falsy. Writing if (todos) instead would not work, because an empty array is truthy. Where 0 or an empty string is a real value rather than a missing one, compare explicitly, for example if (count !== undefined). Truthy and Falsey Values goes further.

Braces can be left out when the block is a single statement, as in if (paid) console.log('Thank you');. Keeping them is safer, because a second line added later without braces runs whatever the condition says.

Steve Griffith covers this topic in his video Basic JavaScript if Statements.