121

I am confused as to when JavaScript returns null or undefined. Also different browsers seem to be returning these differently.

I am seeking 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?

halfer
  • 19,824
  • 17
  • 99
  • 186
copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • Do you have a concreate case? How is this related to events? – Felix Kling Jun 21 '11 at 17:12
  • 21
    See answers below for examples, but the short of it is this: `undefined` means "does not exist". `null` is an ___intentionally___ set value. –  Jun 21 '11 at 17:19
  • 3
    I think you should have a look at: https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals – Felix Kling Jun 21 '11 at 21:36
  • 1
    Sorry, but despite this question is marked as a duplicate, I do not find a proper answer on this page or on the page where a dupliate lives. So, intead of marking the answer, please, read it once again. So that future visitors could find the answer. Or if if the author wanted to know the difference - please esit your question. – FreeLightman Oct 23 '16 at 17:47

6 Answers6

124

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

Cory Gross
  • 36,833
  • 17
  • 68
  • 80
  • Great point; you can set undefined to a value accidentally and not get any useful errors for tracking down where it came from. – Dmytro Nov 06 '16 at 04:36
81

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.

alex
  • 479,566
  • 201
  • 878
  • 984
kennebec
  • 102,654
  • 32
  • 106
  • 127
  • 2
    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 – Mark Lakewood May 31 '12 at 03:01
  • 3
    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" – ProVega Apr 17 '14 at 21:29
50

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
Bjorn
  • 69,215
  • 39
  • 136
  • 164
  • 5
    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. – Andy E Jun 21 '11 at 17:23
  • @Andy - +1, I was trying to think of a case when you could get `null` anywhere without typing it :) –  Jun 21 '11 at 17:25
  • @AndyE: Right, but then, the DOM objects are not part of JavaScript ;) – Felix Kling Jun 21 '11 at 17:25
  • @Felix King - That's a triviality for most people :) –  Jun 21 '11 at 17:25
  • @Felix: of course but I suspect the OP doesn't know that, hence the may or may not be worth mentioning part ;-) – Andy E Jun 21 '11 at 17:26
  • @cwolves: Maybe. But there is still a difference. – Felix Kling Jun 21 '11 at 17:27
  • 2
    @AndyE: I agree, it's definitely worth mentioning it. – Felix Kling Jun 21 '11 at 17:27
  • 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 – copenndthagen Jun 21 '11 at 17:28
  • @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`. – Felix Kling Jun 21 '11 at 17:30
  • hmthr, can you paste the code for getCookie function please. – Bjorn Jun 21 '11 at 17:31
  • I actually took it from http://www.arachna.com/edu/tutorials/mini/cookies/javascript.html – copenndthagen Jun 21 '11 at 17:48
  • 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 ''` – Bjorn Jun 21 '11 at 17:54
  • +1 for null of of type object and undefined is of type undefined. – defau1t Feb 20 '13 at 14:14
9

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    Also, functions with no return statement or just "return" with no value. –  Jun 21 '11 at 17:17
  • 1
    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? – nnnnnn Jun 22 '11 at 04:11
3

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.

Pranav 웃
  • 8,469
  • 6
  • 38
  • 48
DiegoS
  • 98
  • 6
  • 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`. – Lawrence Dol Feb 22 '14 at 21:11
0

A property, when it has no definition, is undefined. null is an object. It's type is null. undefined is not an object, its type is undefined.

This is a good article explaining the difference and also giving some examples.

null vs undefined

alex
  • 479,566
  • 201
  • 878
  • 984
Alex
  • 249
  • 1
  • 6
  • 1
    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. – Eneko Oct 11 '14 at 14:54
  • 2
    `null` is **not** an object, despite what `typeof` says. – alex Jan 27 '16 at 10:45