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 braces console.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:

  1. Create a variable age with a value of 20.
  2. If age is greater than 17, execute the code in the curly braces.
  3. age is greater than 17, so it prints You 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

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

1/9

Introduction to Conditionals | Start Coder