Can someone help me by explaining the difference. From what I understand the === does an exact match but what does this mean when comparing with null ?
-
See http://stackoverflow.com/a/359509/2958164 – Phillip Kinkade Dec 19 '13 at 17:28
-
`undefined === null` is `false`, `undefined == null` is `true` -> in most cases you would use the `==` to handle both `null` and `undefined` at the same time. – Vedran Jan 27 '22 at 10:04
5 Answers
What does this mean when comparing with null?
It means exactly what you already said: It checks whether the value is exactly null.
a === null is true if the value of a is null.
See The Strict Equality Comparison Algorithm in the specification:
1. If
Type(x)is different fromType(y), return false.
2. IfType(x)is Undefined, return true.
3. IfType(x)is Null, return true.
So, only if Type(a) is Null, the comparison returns true.
Important: Don't confuse the internal Type function with the typeof operator. typeof null would actually return the string "object", which is more confusing than helping.
a == null is true if the value of a is null or undefined.
See The Abstract Equality Comparison Algorithm in the specification:
2. If
xisnullandyisundefined, return true.
3. Ifxisundefinedandyisnull, return true.
- 756,363
- 169
- 1,062
- 1,111
=== means it checks both the value and the type of the variables. For example pulled from the w3c page, given x = 5, x is an int, so x==="5" is false because it is comparing and int to string and x ===5 is true because it is both an int and the right value.
- 11
-
3Good example, but OP is asking specifically regarding the comparison with `null` case. – adamdunson Dec 19 '13 at 17:53
=== is strict operator it not only compare value, but also type of variables so
string===string
int===int
== only compare values.
- 27,470
- 11
- 72
- 109
Using the triple equals, the values must be equal in type as well.But not in ==.
i.e
1==true // this return true
1===true // but return false
a==null // will true if a is null or undefined
- 1,890
- 1
- 12
- 15
1==true will be true
but 1===true will be false
eg. === compares on data type level while using == JavaScript will typecast by it self
- 4,482
- 3
- 26
- 35