JavaScript - 6

JavaScript - 6: Conditionals (if / else)

Conditionals let JavaScript make decisions.

Instead of always running the same instructions, your program can check whether something is true and choose what to do next.

In this lesson, you will use if, else if, and else to print a different message depending on a score.

Your challenge: Create a score variable and make JavaScript choose between Excellent!, Good job!, and Keep practicing!.

✦ JavaScript Editor
▶ Live Output

What is a conditional?

A conditional lets your program ask a question.

For example: score >= 90 asks whether the value stored in score is greater than or equal to 90.

The result of that comparison is either true or false.

Start with if

An if statement runs its code only when its condition is true.

For example: if (score >= 90)

If the score is 90 or higher, the code inside the braces runs.

What does >= mean?

The operator >= means greater than or equal to.

So: score >= 90 is true for values such as 90, 95, and 100.

It is false for values such as 89 or 50.

Add another possibility with else if

If the first condition is false, JavaScript can check another one.

For this lesson, the second check is: score >= 70

This means a score from 70 through 89 should print: Good job!

Finish with else

The final else does not need another condition.

It means: "If none of the earlier conditions were true, run this code instead."

So any score below 70 prints: Keep practicing!

The order matters

JavaScript checks the conditions from top to bottom and stops when it finds the first matching branch.

That is why the 90 check should come before the 70 check.

A score of 95 is also greater than 70, but you want it to receive the more specific Excellent! result first.

Experiment with boundary values:

Try changing score to: 90, 89, 70, and 69.

These values are useful because they sit directly around the points where the result changes.

Try more comparison operators:

JavaScript also has operators such as:

> greater than
< less than
>= greater than or equal to
<= less than or equal to

You will use comparisons often when programs need to make decisions.

Extra experiment:

Create a variable called temperature.

Use a conditional to print one message if the temperature is above 25 and another message if it is 25 or lower.

Good JavaScript habit: Arrange your conditions from the most specific or highest-priority case to the more general cases. This makes decision logic easier to understand and helps avoid unexpected results.

👀 Show Solution
let score = 85;

if (score >= 90) {
  console.log("Excellent!");
} else if (score >= 70) {
  console.log("Good job!");
} else {
  console.log("Keep practicing!");
}

With a score of 85, the first condition is false, but the second condition is true, so JavaScript prints Good job!.

Try changing the score to values above 90 and below 70 to see the other branches run.