Hi, I’m just wondering what the difference is between == and ===. I searched for it but didn’t find anything that explained me the key differences.
@JEroi The difference between the two is this ===
is strictly equal 2 and ‘2’ are not equal but this ==
is loosely equal 2 and ‘2’ are equal. The reason they are not equal on the first one is because ‘2’ is a string. Hope this helps. Welcome to the FreeCodeCamp Forums and Happy Coding!
If you want to find some more “official” documentation about this stuff a good phrase/term to google is “equality operator(s)”.
“Operator” is the generic term for things like ===
, +
, >=
, and so on.
There are “unary” operators which operate on a single value, like i++
(++
is the operator)
Binary operators work with two values: something == somethingElse
.
There is also one “ternary” operator in javascript - which operates on 3 values! See if you can figure out what it is. (Let me know if you have trouble )
Here’s are some quick links to details of the equality operators in js:
You’ll see there are actually more ways to compare values than just ==
and ===
too
As a rule of thumb, never use loose equality ==
in JavaScript. Just don’t. Unless you’re absolutely aware of what you’re doing.
console.log('2'=== 2) //false
console.log('2'== 2) //true
the strict equality (===
) is type sensitive
Calling it loose comparison kind of hides the actual implementation details, which isn’t great for beginners. It’s called loose because that is the opposite of strict.
The ==
operator does implicit type coercion/conversion. The fact that 1 == '1'
is true
is not because they are being loosely compared. It is because the string is being converted to a numeric value. So you are in fact doing 1 == 1
but you didn’t do the conversion explicitly yourself.