The if statement
Learn how to check a condition with if and the code block.
The if statement: condition-based code
In JavaScript, the if statement runs code when a condition is true. A condition is an expression whose result is true or false; this is called a boolean expression.
The syntax looks like this:
if (condition) {
// runs when condition is true
}For example, to decide whether someone can drive based on their age, the condition would be age >= 18. When the condition is true the block runs; when it is false nothing happens.
Code blocks and curly braces
In an if statement, the code to run goes between curly braces { }. This is called a code block and it groups multiple statements together.
if (age >= 18) {
console.log("Can drive");
console.log("Go to the exam");
}You can use a block even for a single statement; the braces still improve readability and prevent mistakes. You can put as many statements as you like inside.
Exercise Write an if statement - age check
Write an if statement. When the age variable is 18 or greater, log a message with console.log (for example 'Can drive'). The condition must be age >= 18.
Show example solution
let age = 20;
if (age >= 18) {
console.log("Can drive");
}
Test yourself
-
For the if block to run, what must the condition be?
- The condition must be false
- The condition must be true
- The condition must be a number
- The condition must be a string
Show answer
The condition must be true — Correct. The if block runs only when the condition is true.
-
Start the if statement
let age = 18; ____ (age >= 18) { console.log("Can drive"); }Show answer
let age = 18; if (age >= 18) { console.log("Can drive"); } -
Match the parts of an if statement
- if
- Starts the conditional
- (age >= 18)
- Condition (boolean expression)
- { ... }
- Code block
- console.log
- Statement to run