Assign or Compare?

The equals sign has two different jobs in JavaScript, depending on how many of them you write:

  • = assigns: it stores the value on the right in the variable on the left. score = 10 means “score is now 10”.
  • === compares: it asks whether two values are equal, and it changes nothing. score === 10 means “is score 10?”

Writing = instead of === in a condition is one of the most common bugs, and JavaScript doesn't warn you about it:

let age = 15;
if (age = 18) {
    console.log("Happy 18th birthday!");
}
console.log("Age:", age);

This prints:

Happy 18th birthday!
Age: 18

The condition age = 18 doesn't ask anything. It changes age to 18, and the if then uses that 18 as its condition. A number other than 0 counts as true, so the block runs. That's two bugs at once: a wrong message, and a variable that has lost its value.

If age were a constant (const age = 15;), you'd at least get an error, because a constant can't be changed: TypeError: Assignment to constant variable. That's another reason to use const for values that don't change.

JavaScript also has ==, with two equals signs. Before comparing, it converts both values to the same type, so "5" == 5 is true, although one is text and the other a number. With three equals signs, "5" === 5 is false: text and a number are never equal. Such conversions lead to surprises, so always use === and !==, never == and !=.

Instructions

Run the program. The student has 40 points, yet it prints Perfect score! and Points: 100. Fix the condition so that it compares points with 100 using ===. Then the program prints only Points: 40.

Add an else branch that prints Keep practicing.

Start programming for free

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

Or sign up with:

4/11