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 enterWhat does an if statement consist of?
- The
ifkeyword 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
agewith a value of20. - If
ageis greater than17, execute the code in the curly braces. ageis 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