I generally don't prefer using == but today i was just experimenting with the following code including == and the results are a bit confusing to me. Can someone please explain what is happening?
All these are falsy values:
'', 0, false, undefined, null
Suppose i did:
if (undefined == null) {
alert('a');
} else {
alert('b');
}
The statements below give true:
null == undefined
0 == ''
false == ''
0 == false
But why does the code below return false?
undefined == 0
undefined == ''
null == 0
= 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.
The equality operator ( == ) checks whether its two operands are equal, returning a Boolean result. Unlike the strict equality operator, it attempts to convert and compare operands that are of different types.
In light of this, most JavaScript experts recommend always using the triple-equals operator, and never using double-equals. The triple-equals operator, as you've probably figured out by now, never does type coercion. So whenever you use triple-equals, you're doing an exact comparison of the actual values.
Triple equals ( === ) will do the same comparison as double equals (including the special handling for NaN , -0 , and +0 ) but without type conversion; if the types differ, false is returned.
Because 0
, false
and ''
are "values" while null
is "absence of value" and undefined
is "absence of definition".
Thus, you can compare "values" with each other, same for "non-values". But you can't compare "values" with "non-values".
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