Possible Duplicate:
JavaScript === vs == : Does it matter which “equal” operator I use?
I can understand why ===
is necessary when comparing numbers, booleans, empty strings, etc, due to unexpected type conversions e.g.
var foo = 1;
var bar = true;
// bar == foo => true
// bar === foo => false
But can ==
ever introduce a bug when comparing a variable to a non-empty string literal? Is it more efficient to use ==
over ===
in this case?
= Vs == VS === in JavaScript = in JavaScript is used for assigning values to a variable. == in JavaScript is used for comparing two variables, but it ignores the datatype of variable. === is used for comparing two variables, but this operator also checks datatype and compares two values.
== Operator: This operator is used to check the given values are equal or not. If yes, it returns true, otherwise it returns false. === Operator: This operator is used to check the given values and its data type are equal or not. If yes, then it returns true, otherwise it returns false.
Explanation of the example: In the above example, when str1 and str2 are compared after using the toUpperCase method, the expression JAVASCRIPT == JAVASCRIPT would return true as they are the same strings after both being in upper case. Here, the equality operator (==) is used to check if both the strings are the same.
Yes, === can compare two strings, giving true or false as a result. The other examples you saw were talking about comparing strings when sorting lists of them.
This has been asked here a lot so I'll just let a better poster then myself answer.
Take a look here: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html
The 3 equal signs mean "equality without type coercion". Using the triple equals, the values must be equal in type as well.
0==false // true 0===false // false, because they are of a different type 1=="1" // true, auto type coercion 1==="1" // false, because they are of a different type
source Difference between == and === in JavaScript
It is a good practice to always use the identity operators (!==
and ===
) and perform type coercion manually only when you need to (e.g. Boolean(someVar)
or Number(someVar)
).
A fun fiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With