Understand Control Flow
Sometimes we want some code to only run under certain conditions. The if..else
statement is one of the most common ways to affect the control flow.
Since a different blocks of code run under different conditions, the if...else
statement is a type of conditional statement.
if...else
The if
block of code will run if the condition is true. If the condition is false the else
block of code runs.
let varNumber = 1000000;if (varNumber > 1000) {console.log('This number is bigger than 1000');} else {console.log('This number is smaller than or equal to 1000');}
It is also valid code to run only the if
statement. This is common when you just want a piece of code to run under a condition but nothing to happen if the condition is false.
let aUser = 'Rachel';if (aUser === 'Rachel') {console.log('Hi, Rachel!');}
There is also an option to use an else if
clause if you want to evaluate more than one statement before else
.
let yourHeightInCentimeters = 170;if (yourHeightInCentimeters < 158) {console.log('You should buy the extra small bike!');} else if (yourHeightInCentimeters < 168) {console.log('You should buy the small bike!');} else if (yourHeightInCentimeters < 178) {console.log('You should buy the medium bike!');} else if (yourHeightInCentimeters < 185) {console.log('You should buy the large bike!');} else if (yourHeightInCentimeters < 193) {console.log('You should buy the extra large bike!');} else {console.log('You should buy the extra extra large bike!');}