Let's quickly run through all the comparison operators, to know what they're called and how they work.
Equality operator: ==
We'll start with the equality operator, which compares two values. When using this comparison operator, as well as most of the other ones, the result is a boolean - either the comparison is true or false. Therefore, you will often use them in combination with an if statement, like this:
let n1 = prompt("Please input a number"); if(n1 == 42) alert("Correct answer!");
Notice how we use the assignment operator (=) on the first line, and then the equality comparison operator (==) on the next line. The visual difference is subtle, but make sure to learn the difference - it's very important.
Inequality operator: !=
But, what if you need to ask whether something is NOT the same? No worries, you can negate the equality operator using an exclamation point, to mean the exact opposite. Here's an example:
let n1 = prompt("Please input a number"); if(n1 != 42) alert("Wrong answer - it should be 42!");
Notice how I simply changed == to != to negate the condition.
Greater than/less than: > and <
let n1 = prompt("Please input a number between 1 and 10"); if(n1 < 1) alert("Too low!"); if(n1 > 10) alert("Too high!");
Greater/less than or equal to: >= and <=
let n1 = prompt("Please input a number between 1 and 10"); if(n1 <= 0) alert("Too low!"); if(n1 >= 11) alert("Too high!");
Strict equality: ===
I teased a bit about this in the beginning of the article: There's a more strict comparison operator, to do the same thing as we just did above, but in a more strict way. But what is all this strictness about and why do we need it?
let n1 = "42", n2 = 42; if(n1 == n2) alert("A match!");
let n1 = "42", n2 = 42; if(n1 === n2) alert("A match!"); else alert("Sorry, no strict match!");
Strict inequality: !==
And of course, you can check for strict inequality the same way, by changing one of the three equal signs into an exclamation point:
let n1 = "42", n2 = 42; if(n1 !== n2) alert("Sorry, no strict match!"); else alert("A match!");