This chapter highlights some common mistakes made in JavaScript.
JavaScript programs can produce unexpected results if a programmer mistakenly uses the assignment operator (=) instead of the comparison operator (==) in an if statement.
In the following example, the if statement returns false (as expected) because x is not equal to 10:
let x = 0; if (x == 10) |
This if statement returns true (possibly not as expected) because 10 is considered a truthy value.
let x = 0; if (x = 10) |
This if statement returns false (possibly not as expected) because 0 is considered falsy.
let x = 0; if (x = 0) |
An assignment expression always returns the value that has been assigned. |
In a regular comparison, the data type is ignored. This if statement returns true:
let x = 10; let y = “10”; if (x == y) |
In strict comparison, the data type is taken into account. This if statement returns false:
let x = 10; let y = “10”; if (x == y) |
In strict comparison, the data type is important. This if statement returns false:
let x = 10; let y = “10”; if (x === y) |
It’s a common mistake to overlook that switch statements use strict comparison.
This switch case will trigger an alert:
let x = 10; switch(x) { case 10: alert(“Hello”); } |
This switch case will not trigger an alert:
let x = 10; switch(x) { case “10”: alert(“Hello”); } |