What Is The Equality Operator?
The equality operator lets you check if two statements are equal, and the result will be a boolean value.
Basically, it compares statements.
Types of Equality Operators:
We have two types of Equality operators:
Strict Equality Operator (
==
)Loose Equality Operator (
===
)
Strict Equality Operator (===
)
In the strict equality operator (===
), both the value and type have to be the same.
Syntax:
x === x
In this example:
20 === 20
// true
Both 20s have the same value and type. (both are numbers). Therefore the result is true.
But in this one:
20 === "20"
// 20 is a number
// "20" is s string
// value and type are not the same
// so the result will be false
If we log both 20s in the console, one is a number and the other is s string:
console.log(typeof 20) // number
console.log(typeof "20") // string
The strict equality operator (===
) only returns true when both the value and type are the same. Since we have different types here, the result is false.
Now, if both are numbers, the results would be true:
20 === 20
// both 20s are numbers and the same type
Loose Equality Operator (==
)
Loose equality operator (==
) checks if two values are equal, but iit doesn't care much about the type of data the values are.
Syntax:
x == y
Example:
20 == 20
// true
And
20 == "20"
// true
Since loose equality operator does not care about the type and value, the result in both examples are true.
Tip : ๐ก
Loose equality (==
) can be tricky because it can lead to unexpected results and it's best to use strict equality operator (===
) to avoid any unwanted bugs in your codes.
To recap
Equality operator allows you to check to see if two statements are equal and the result will be a boolean.
We have two types of equality operator (
==
and===
).Strict equality operator (
===
) only returns true when both value and type are the same.Loose equality operator (
==
) does not care about the value and type.it's best to use strict equality operator (
===
)
Awesome. Now you got this equality operator thing figured out! Practice makes perfect, so try writing some code examples to test them out. Think of it like a code experiment to see what makes it say "true" or "false." The more you play, the better you'll be!
(Find me on Twitter ๐ฆ @nazanin_ashrafi)