Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type casting when == used instead of === [duplicate]

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
like image 839
AMY Avatar asked Apr 14 '14 09:04

AMY


People also ask

Should I use == or === in JavaScript?

= 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.

What is == operator in JavaScript?

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.

Should I use triple equals JavaScript?

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.

What is the difference between double equal to and triple equal to in JavaScript?

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.


1 Answers

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".

like image 100
avetisk Avatar answered Oct 06 '22 09:10

avetisk