testndtv testndtv - 2 months ago 14
Javascript Question

When is null or undefined used in JavaScript?

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?

Answer

The DOM methods getElementById(), nextSibling(), childNodes[n], parentNode() and so on return null (defined but having no value) when the call does not return a node object.

The property is defined, but the object it refers to does not exist.

This is one of the few times you may not want to test for equality-

if(x!==undefined) will be true for a null value

but if(x!= undefined) will be true (only) for values that are not either undefined or null.

Comments