I am really confused as to when JavaScript returns null
or undefined
. Also different browsers seem to be returning these differently.
Could you please give some examples of null
/undefined
with the browsers that return them.
While I am now clear on the undefined
aspect, I am still not 100% clear on null
. Is it similar to a blank value?
E.g. You have a text box which does not have any value set. Now when you try to access its value, will it be null
or undefined
and are they similar?
I find that some of these answers are vague and complicated, I find the best way to figure out these things for sure is to just open up the console and test it yourself.
var x;
x == null // true
x == undefined // true
x === null // false
x === undefined // true
var y = null;
y == null // true
y == undefined // true
y === null // true
y === undefined // false
typeof x // 'undefined'
typeof y // 'object'
var z = {abc: null};
z.abc == null // true
z.abc == undefined // true
z.abc === null // true
z.abc === undefined // false
z.xyz == null // true
z.xyz == undefined // true
z.xyz === null // false
z.xyz === undefined // true
null = 1; // throws error: invalid left hand assignment
undefined = 1; // works fine: this can cause some problems
So this is definitely one of the more subtle nuances of JavaScript. As you can see, you can override the value of undefined
, making it somewhat unreliable compared to null
. Using the ==
operator, you can reliably use null
and undefined
interchangeably as far as I can tell. However, because of the advantage that null
cannot be redefined, I might would use it when using ==
.
For example, variable != null
will ALWAYS return false if variable
is equal to either null
or undefined
, whereas variable != undefined
will return false if variable
is equal to either null
or undefined
UNLESS undefined
is reassigned beforehand.
You can reliably use the ===
operator to differentiate between undefined
and null
, if you need to make sure that a value is actually undefined
(rather than null
).
Null
and Undefined
are two of the six built in types.4.3.9 undefined value
primitive value used when a variable has not been assigned a value
4.3.11 null value
primitive value that represents the intentional absence of any object value