Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quantum duality: variable is null and undefined at the same time?

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?

like image 582
Art Avatar asked Nov 19 '10 03:11

Art


People also ask

Is null == undefined?

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.

How null == undefined is true?

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.

What is the relationship between null and undefined?

null is an assigned value. It means nothing. undefined means a variable has been declared but not defined yet.

Why does JavaScript have both null and undefined?

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 .


1 Answers

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

like image 132
SLaks Avatar answered Nov 14 '22 22:11

SLaks