Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

    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.

  2. 2

    Add an else branch that prints Keep practicing.

Back

4/13

  1. 1. The if Statement
  2. 2. The else Branch
  3. 3. Comparison Operators
  4. 4. Assign or Compare?
  5. 5. Quiz: Assign or Compare?
  6. 6. Boolean Values
  7. 7. More Options: else if
  8. 8. Logical Operators: And
  9. 9. Logical Operators: Or
  10. 10. Quiz: Logical Operators
  11. 11. Negation
  12. 12. Nested Conditions
  13. 13. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.