When is null or undefined used in JavaScript?

113,799

Solution 1

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.

Solution 2

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

According to the ECMAScript 5 spec:

  • Both 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

Solution 3

You get undefined for the various scenarios:

You declare a variable with var but never set it.

var foo; 
alert(foo); //undefined.

You attempt to access a property on an object you've never set.

var foo = {};
alert(foo.bar); //undefined

You attempt to access an argument that was never provided.

function myFunction (foo) {
  alert(foo); //undefined.
}

As cwolves pointed out in a comment on another answer, functions that don't return a value.

function myFunction () {
}
alert(myFunction());//undefined

A null usually has to be intentionally set on a variable or property (see comments for a case in which it can appear without having been set). In addition a null is of type object and undefined is of type undefined.

I should also note that null is valid in JSON but undefined is not:

JSON.parse(undefined); //syntax error
JSON.parse(null); //null

Solution 4

I might be missing something, but afaik, you get undefined only

Update: Ok, I missed a lot, trying to complete:

You get undefined...

... when you try to access properties of an object that don't exist:

var a = {}
a.foo // undefined

... when you have declared a variable but not initialized it:

var a;
// a is undefined

... when you access a parameter for which no value was passed:

function foo (a, b) {
    // something
}

foo(42); // b inside foo is undefined

... when a function does not return a value:

function foo() {};
var a = foo(); // a is undefined

It might be that some built-in functions return null on some error, but if so, then it is documented. null is a concrete value in JavaScript, undefined is not.


Normally you don't need to distinguish between those. Depending on the possible values of a variable, it is sufficient to use if(variable) to test whether a value is set or not (both, null and undefined evaluate to false).

Also different browsers seem to be returning these differently.

Please give a concrete example.

Solution 5

Regarding this topic the specification (ecma-262) is quite clear

I found it really useful and straightforward, so that I share it: - Here you will find Equality algorithm - Here you will find Strict equality algorithm

I bumped into it reading "Abstract equality, strict equality, and same value" from mozilla developer site, section sameness.

I hope you find it useful.

Share:
113,799
copenndthagen
Author by

copenndthagen

Buy some cool JavaScript related merchandise from; https://teespring.com/stores/technical-guru-2

Updated on September 26, 2020

Comments

  • copenndthagen
    copenndthagen over 3 years

    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?

  • None
    None almost 13 years
    Also, functions with no return statement or just "return" with no value.
  • Andy E
    Andy E almost 13 years
    It might not be worth mentioning, but DOM objects can be initialized with null values for their members. Most notably for events (although not the case in Firefox due to a bug) - see document.createElement("a").onclick - but also for some other properties.
  • None
    None almost 13 years
    @Andy - +1, I was trying to think of a case when you could get null anywhere without typing it :)
  • Felix Kling
    Felix Kling almost 13 years
    @AndyE: Right, but then, the DOM objects are not part of JavaScript ;)
  • None
    None almost 13 years
    @Felix King - That's a triviality for most people :)
  • Andy E
    Andy E almost 13 years
    @Felix: of course but I suspect the OP doesn't know that, hence the may or may not be worth mentioning part ;-)
  • Felix Kling
    Felix Kling almost 13 years
    @cwolves: Maybe. But there is still a difference.
  • Felix Kling
    Felix Kling almost 13 years
    @AndyE: I agree, it's definitely worth mentioning it.
  • copenndthagen
    copenndthagen almost 13 years
    Ok...thx a lot..now lets say i have a function getCookie in JS..If for some reason, it could not find the fn declaration for getCookie and I check using if getCookie(), what will it return...null or undefined AND is only writing if getCookie() Enough
  • Felix Kling
    Felix Kling almost 13 years
    @hmthr: Then you would have to write if(getCookie) without parenthesis after the name. And it would not matter whether it is null or undefined, both evaluate to false.
  • Bjorn
    Bjorn almost 13 years
    hmthr, can you paste the code for getCookie function please.
  • copenndthagen
    copenndthagen almost 13 years
  • copenndthagen
    copenndthagen almost 13 years
    Please also see my updated question..
  • Bjorn
    Bjorn almost 13 years
    hmthr, an empty textbox returns an empty string for its value. It's not the same as no content. var t = document.createElement('textarea'); alert(t.value); //Prints an empty string ''
  • nnnnnn
    nnnnnn almost 13 years
    King - I know you know this, but if(variable) is only a reasonable test when you're sure that any non-null/non-undefined value will not evaluate to false. You did say "depending on the possible values", but perhaps that could be made clearer?
  • Mark Lakewood
    Mark Lakewood almost 12 years
    surely the second instance if(x != undefined) is a side effect of != trying to typecast x to compare to undefined. This seems to me a red herring. null shouldnt equal undefined. it appears to me that they are different things
  • defau1t
    defau1t about 11 years
    +1 for null of of type object and undefined is of type undefined.
  • Lawrence Dol
    Lawrence Dol about 10 years
    Thanks for reminding me about abstract vs. strict equality. Was puzzled for a while today why an argument I passed as null was ==undefined. Duh - null is ==undefined, but is not ===undefined! Or in your words, null is abstractly equal to undefined but is not strictly equal to undefined.
  • ProVega
    ProVega about 10 years
    This is dangerous and sub-optimal. This works because "undefined" is indeed undefined. But "undefined" is not a reserved word in JavaScript. So you can just do this: var undefined = "Magic!"; // Yes this works Now your code may or may not work. It is better to do a typeof(x) !== "undefined"
  • Eneko
    Eneko over 9 years
    That article is plain wrong. Is says that when people write if (foo == null) what they really mean is if (!foo), and it has nothing to do. First is only true if foo is undefined or null, but the last one would also be true if foo = empty string, zero, false or NaN.
  • user3167101
    user3167101 over 8 years
    null is not an object, despite what typeof says.
  • Dmytro
    Dmytro over 7 years
    Great point; you can set undefined to a value accidentally and not get any useful errors for tracking down where it came from.