Comparison Operators
Learn and practice comparison operators in JavaScript.
We'll cover the following
We often need to compare values when programming, and there’s a number of ways to do this.
Equality
The equality operator can be used to check if two values are equal to each other. Most programming languages use the double-equals operator (==
) to check for equality.
For example, if we wanted to know if the variable answer
is , we could write:
answer == 42;
This would return true
if the answer was and false
if it wasn’t.
Why double-equals and not a single equals sign? Recall that we learned that the single equals sign was used for assignment. This means that the following code will assign the value of 42
to the variable answer
, rather than check if they are equal:
answer = 42;
Assigning values instead of checking for equality is a common mistake that can often confuse new programmers.
Soft equality
JavaScript does things a little differently from other languages. It has the double-equals operator (==
), known as soft equality, and the triple-equals operator (===
), known as hard equality.
What’s the difference between hard and soft equality? Well, it’s all to do with how strict JavaScript is when it comes to deciding whether or not two values are equal.
Consider the following example. Let’s say we want to check if the variable answer
is equal to the value of . We could check it using soft equality:
Get hands-on with 1400+ tech skills courses.