The if statement
- Node.js course
- Beginner
- Lesson 36/116
- 4 min
Learn how to check a condition with if.
The if statement
To run a block of code when a condition is true you use the if statement. The form is if (condition) { ... }. The condition goes inside parentheses, the code to run inside curly braces.
For example if (age >= 18) { console.log("Adult"); } prints "Adult" when age is 18 or more; otherwise it does nothing. The condition is any expression that yields true or false. Comparison operators (>, <, ==, >=, <=) are the most common ones.
Comparison operators
Condition expressions use comparison operators. === tests equal value and same type; !== means not equal or different type. > is greater than, < is less than, >= is greater or equal, <= is less or equal.
In Node.js === (three equals) is preferred; == (two equals) does type coercion and can lead to surprising results. For example 5 === "5" is false but 5 == "5" is true. Using === for type-safe comparison is a good habit.
Practice Check the age
The age variable is set to 20. Write an if statement: when the condition age >= 18 holds, call console.log("Adult"). The output on a single line must be Adult.
Starter code
const age = 20;
// Write the if statement hereSample solution
const age = 20;
if (age >= 18) {
console.log("Adult");
}Expected output
Adult
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does if (5 > 3) { console.log("yes"); } print?
if (5 > 3) { console.log("yes"); }- yes Correct answer
- nothing
- false
- 5 3
Explanation: The condition 5 > 3 is true; "yes" is printed.
2 Write the if condition
const age = 20;
____ (age >= 18) {
console.log("Adult");
}
const age = 20;
if (age >= 18) {
console.log("Adult");
}
Explanation: if checks a single condition.
3 Match each operator to its meaning
| Term | Meaning |
|---|---|
=== |
Equal and same type |
!== |
Not equal |
> |
Greater than |
<= |
Less or equal |