Consider following JavaScript code (tested in Firefox):
function f(a) {
if (a == undefined) {
alert('undefined');
}
if (a == null) {
alert('null');
}
}
f();
Both alerts are shown, suggesting that both statements are true.
Could you provide a reasonable explanation?
It means null is equal to undefined but not identical. When we define a variable to undefined then we are trying to convey that the variable does not exist . When we define a variable to null then we are trying to convey that the variable is empty.
null == undefined evaluates as true because they are loosely equal. null === undefined evaluates as false because they are not, in fact, equal. <null_variable> === null is the best way to strictly check for null.
null is an assigned value. It means nothing. undefined means a variable has been declared but not defined yet.
The value null represents the intentional absence of any object value. It's never assigned by the runtime. Meanwhile any variable that has not been assigned a value is of type undefined . Methods, statements and functions can also return undefined .
==
is a "soft" equality operator.
It uses type coercion to compare two equivalent objects as equal.
All of the following are true:
42 == "42"
0 == false
0 == ""
[] == ""
{} == "[object Object]"
'/(?:)/' == new RegExp
Instead, you should use the ===
operator, which checks for strict equality.
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