The if Statement

So far, your programs have run every line, one after another, from top to bottom. But a program often has to decide what to do: show a warning only if a password is too short, or give a discount only if the customer is a student. We make decisions like that all the time: if it rains, I'll take an umbrella.

In JavaScript, you write a decision with the if statement:

const temperature = 30;
if (temperature > 25) {
    console.log("It's hot, take a cap");
}
console.log("Have a nice day");

This prints:

It's hot, take a cap
Have a nice day

The if statement has three parts:

  • the keyword if (like let and const, a word with a special meaning in JavaScript);
  • a condition in parentheses: temperature > 25. A condition is a question that can only be answered yes (true) or no (false): is the temperature greater than 25?
  • a block of code in curly braces { }. The block runs only if the condition is true, and it can have as many lines as you need.

The lines inside the block are indented by 4 spaces (or with the Tab key). JavaScript doesn't need the indentation, but it shows at a glance which lines belong to the block.

After the block, the program goes on as usual, so Have a nice day is printed either way. If temperature were 10, the condition would be false: the program would skip the block and print only Have a nice day.

Mind the semicolons. The lines inside the block end with ; as usual, but there is no semicolon after if (...). Putting one there is a typical beginner mistake, and JavaScript doesn't report it as an error:

const temperature = 10;
if (temperature > 25); {
    console.log("It's hot, take a cap");
}

This prints:

It's hot, take a cap

The semicolon ends the if statement right there, with nothing to do. The block in curly braces no longer belongs to it, so it runs every time, even at 10 degrees. You don't put a semicolon after the closing } either.

Instructions

Below the variable, write an if statement with the condition monitorPrice < 4000. In its block, print I will buy the monitor.

Below it, write a second if statement with the condition monitorPrice > 4000 that prints It's too expensive. Run the program: it still prints only I will buy the monitor, because 3000 isn't greater than 4000, so the second block is skipped.

Start programming for free

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

Or sign up with:

Back

1/13

Next