Introduction to Conditionals
In life, we often perform actions based on conditions. For example: if it rains, I will take an umbrella. If I have time, I will come.
In programming, we do this using the if
statement. For example:
let age = 20;
if (age > 17) { // if age is greater than 17, execute:
console.log("You can enter");
}
// Prints: You can enter
What does an if
statement consist of?
- The
if
keyword followed by a condition in parentheses(age > 17)
, which is either true or false, followed by the code we want to execute in curly bracesconsole.log("You can enter")
. - This code within curly braces is indented (either using the Tab key or four spaces).
Now let's go through the code step by step:
- Create a variable
age
with a value of20
. - If
age
is greater than17
, execute the code in the curly braces. age
is greater than17
, so it printsYou can enter
.
Instructions
Create a variable monitorPrice
with a value of 3000
.
On the next line, create an if
statement with the condition monitorPrice < 4000
, which if true, will print I will buy the monitor
.
Start programming for free
1/9