889

Why is null considered an object in JavaScript?

Is checking

if ( object == null )
      Do something

the same as

if ( !object )
      Do something

?

And also:

What is the difference between null and undefined?

Rahul
  • 8,599
  • 4
  • 42
  • 78
rahul
  • 174,563
  • 47
  • 223
  • 254
  • 8
    Null is not an object in JavaScript! `typeof null === 'object'` but that's a bug! Here's a [link](https://www.youtube.com/watch?v=JxAXlJEmNMg) Watch all the videos and enjoy :) – CoR Jun 30 '15 at 14:42
  • 1
    I like to use C/C++ as the axiomatic truth for what an undefined and NULL valued variable is, since it's very straightforward. Then see how those definitions compare to other languages' specifications. – samis Feb 03 '16 at 19:24

22 Answers22

1506
(name is undefined)

You: What is name? (*)
JavaScript: name? What's a name? I don't know what you're talking about. You haven't ever mentioned any name before. Are you seeing some other scripting language on the (client-)side?

name = null;

You: What is name?
JavaScript: I don't know.

In short; undefined is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null is where the thing is known to exist, but it's not known what the value is.

One thing to remember is that null is not, conceptually, the same as false or "" or such, even if they equate after type casting, i.e.

name = false;

You: What is name?
JavaScript: Boolean false.

name = '';

You: What is name?
JavaScript: Empty string


*: name in this context is meant as a variable which has never been defined. It could be any undefined variable, however, name is a property of just about any HTML form element. It goes way, way back and was instituted well before id. It is useful because ids must be unique but names do not have to be.

Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997
Rob
  • 46,632
  • 4
  • 70
  • 91
  • 15
    But in JavaScript, the empty string '' is still a boolean false. – Andreas Grech Feb 21 '10 at 21:11
  • 121
    The empty string is not boolean false, but in the context of a conditional it is interpreted as a false(y) value (coercion). – Bryan Matthews Dec 21 '10 at 19:23
  • 24
    For the second case, where name = null, instead of 'I don't know', JavaScript could answer: The null object. Other than that I like the style of the answer. – Jean Vincent Jun 18 '11 at 10:05
  • 17
    Rather than “I don't know”, I'd say the answer for `null` is “nothing”. Null is precisely defined as no value. Void, nil, nada. Nothing. – mikl Aug 13 '11 at 20:09
  • 53
    Love that style of answering. In general, *"You haven't ever mentioned any* `name` *before"* is true. However, declaring a variable without assigning a value to it (`var somevar;`), will surprisingly enough still result in `undefined`. – MC Emperor Jan 10 '12 at 15:40
  • 11
    @MC Emperor - also, you can explicitly set a declared variable to `undefined`, so I agree that the _"You haven't ever mentioned any `name` before"_ is a bit misleading. – jinglesthula Jan 13 '12 at 22:50
  • 5
    This doesn't answer the question of: "Is (object == null) the same as (!object)" – Pakman Mar 14 '12 at 16:31
  • I always thought undefined was same as a null. But now I realized undefined is almost like null of a null. – Churk Mar 29 '12 at 13:56
  • 7
    >Are you seeing some other scripting language on the (client-)side? Hahahaha – Tim van Dalen Nov 02 '12 at 21:16
  • @MC Emperor - It's not really surprising when you consider the difference between de_clare_ and de_fine_. `var somevar` is a variable declaration (a reserved area in memory) whereas `var somevar = 'foo'` is a variable assignment or definition, if you will. If you attempt to reference the value of "somevar", javascript has reserved space and hence knows the variable exists, but since no assignment has been made, javascript lets you know "somevar" exists as nothing more than a declaration by returning "undefined". That's really the only sensible thing it can return. – squidbe Jan 04 '13 at 07:39
  • Tested this on Chrome console and noticed the following: Initialize `var name = null;`. First test: `name == null; // => false` Second test: `name == 'null'; // => true`. This is true since `typeof(name) = 'string'`. The variable `name` is implicitly a string. What a subtlety! – gmajivu May 29 '13 at 14:06
  • @AndreasGrech: [false] is not actually [""], if you put === between the two – alphakevin Jul 08 '13 at 05:22
  • @antmary Indeed, and that's because `===` does not do type coercion. – Andreas Grech Jul 08 '13 at 09:22
  • 3
    I believe you're explanation is not entirely correct (however I could be wrong as well). Undefined is the value which should be used when no value is known. `car is undefined` means that Javascript doesn't know the *value* of car, it does know however what car is. Null represents the absence of a value, there is no relevant value. `car = null` means that there simply is no car. So what you've defined as null is actually undefined, and null is something completely different. – Tiddo Jul 10 '13 at 19:45
  • 2
    @AndreasGrech In Javascript, the empty string is not a Boolean false. It simply evaluates to Boolean false when you use coercion. – Zlatko Sep 01 '13 at 09:57
  • Love the story telling approach :D – luigi7up Sep 09 '16 at 08:24
  • typeof is asking JavaScript for the type of thing the value of a variable is, not for the variable itself. When no variable is ever declared, JavaScript throws a reference error. That should be the first line in your dialog where JS hasn't heard of any 'name' you speak of. If you declare a variable, but don't assign a value or if you assign undefined then that means the thing exists, it just doesn't have a value, therefore the type of that value is undefined. Null on the other hand causes problems. Null is supposed to mean 'no value' but if you ask for `typeof null` you get 'object' WAT. – Costa Dec 01 '16 at 18:59
  • I would like to agree with Tiddo and suggest that the cause of a value being `undefined` is ambiguous whereas `null` is like saying "this space intentionally left blank". – Matt S Jun 08 '17 at 04:13
  • [`name`](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) is a part protected (it can be only a string) property of window. – Nina Scholz Sep 06 '18 at 07:25
  • There is no `is` keyword in JavaScript/ECMAScript, much less an operator, is it? I am referring to the `(name is undefined)` expression. – amn Nov 08 '18 at 09:27
  • This answer is misleading to the point of being incorrect. I have written a referenced answer [below](https://stackoverflow.com/a/64009911/38522). – Ben Aston Sep 23 '20 at 13:23
  • @AndreasGrech In refer to [this](https://stackoverflow.com/questions/801032/why-is-null-an-object-and-whats-the-difference-between-null-and-undefined#comment2274178_802371): No, it is not. It is falsy, but not boolean. – Alexandre Piva May 28 '21 at 19:08
144

The difference can be summarized into this snippet:

alert(typeof(null));      // object
alert(typeof(undefined)); // undefined

alert(null !== undefined) //true
alert(null == undefined)  //true

Checking

object == null is different to check if ( !object ).

The latter is equal to ! Boolean(object), because the unary ! operator automatically cast the right operand into a Boolean.

Since Boolean(null) equals false then !false === true.

So if your object is not null, but false or 0 or "", the check will pass because:

alert(Boolean(null)) //false
alert(Boolean(0))    //false
alert(Boolean(""))   //false
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
kentaromiura
  • 6,229
  • 2
  • 19
  • 15
  • @kentaromiura For us Javascript noobs...maybe only me...what is this Boolean(value) syntax? Casting to a Boolean? – xr280xr Jun 12 '12 at 20:37
  • @xr280xr Yes, it's casting. Try `String(null)` to see another example of casting. You can even do silly things like `Number(null + 2)`... but you shouldn't :-). Excellent answer from kentaromiura. – squidbe Jan 04 '13 at 07:06
  • Remember `typeof` is an operator. You wouldn't wrap the operand in parenthesis for the same reason you wouldn't write `var sum = 1 +(1);`. – alex Jan 27 '16 at 10:51
128

null is not an object, it is a primitive value. For example, you cannot add properties to it. Sometimes people wrongly assume that it is an object, because typeof null returns "object". But that is actually a bug (that might even be fixed in ECMAScript 6).

The difference between null and undefined is as follows:

  • undefined: used by JavaScript and means “no value”. Uninitialized variables, missing parameters and unknown variables have that value.

    > var noValueYet;
    > console.log(noValueYet);
    undefined
    
    > function foo(x) { console.log(x) }
    > foo()
    undefined
    
    > var obj = {};
    > console.log(obj.unknownProperty)
    undefined
    

    Accessing unknown variables, however, produces an exception:

    > unknownVariable
    ReferenceError: unknownVariable is not defined
    
  • null: used by programmers to indicate “no value”, e.g. as a parameter to a function.

Examining a variable:

console.log(typeof unknownVariable === "undefined"); // true

var foo;
console.log(typeof foo === "undefined"); // true
console.log(foo === undefined); // true

var bar = null;
console.log(bar === null); // true

As a general rule, you should always use === and never == in JavaScript (== performs all kinds of conversions that can produce unexpected results). The check x == null is an edge case, because it works for both null and undefined:

> null == null
true
> undefined == null
true

A common way of checking whether a variable has a value is to convert it to boolean and see whether it is true. That conversion is performed by the if statement and the boolean operator ! (“not”).

function foo(param) {
    if (param) {
        // ...
    }
}
function foo(param) {
    if (! param) param = "abc";
}
function foo(param) {
    // || returns first operand that can't be converted to false
    param = param || "abc";
}

Drawback of this approach: All of the following values evaluate to false, so you have to be careful (e.g., the above checks can’t distinguish between undefined and 0).

  • undefined, null
  • Booleans: false
  • Numbers: +0, -0, NaN
  • Strings: ""

You can test the conversion to boolean by using Boolean as a function (normally it is a constructor, to be used with new):

> Boolean(null)
false
> Boolean("")
false
> Boolean(3-3)
false
> Boolean({})
true
> Boolean([])
true
Axel Rauschmayer
  • 22,683
  • 4
  • 21
  • 15
  • 1
    Why reference `+0` and `-0` seperately if `+0 === -0` ? – Raynos Nov 07 '11 at 03:09
  • 6
    Probably because you can still distinguish `+0` and `-0`: `1/+0 !== 1/-0`. – neo Aug 01 '13 at 08:21
  • 1
    This answer links to a post that links back to this answer as source... probably meant to link to this instead http://www.2ality.com/2013/10/typeof-null.html – Ricardo Tomasi Nov 27 '13 at 17:47
  • Oh right, like in C, where uninitialized variable declarations are considered undefined (old versions could actually contain a previous programs data). – samis Feb 03 '16 at 19:19
  • Programmers can also use `undefined` to indicate "no value", and JS can also use `null` to indicate "no value". – Oriol Aug 09 '16 at 23:02
  • @Axel Raoschmayer I don't blame you. Netscape programmers, had it wrong all the way until very recently. I believe it was corrected in Firefox 5 or later. They didn't know that null is a supplement for a missing property;method;object-reference, whereas undefined: a missing value. Undefined is typeles, null is not. null reflects an undefined object undefined an undefined primitive. That's why when typecasting, only null == undefined > true, but no other falsy primitives or objects . That's because when you take away the type from null - what remains is a naked undefined. – Bekim Bacaj Oct 22 '16 at 23:29
  • 6
    "But that is actually a bug (that might even be fixed in ECMAScript 6)" – source? – Gajus Jan 31 '17 at 11:47
  • I think @neo is the one. – jchook Sep 22 '17 at 02:25
  • It won't ever be fixed. If it gets fixed all the internet could break down. It's the same problem of NaN === NaN – Cristian Traìna Apr 04 '19 at 15:14
  • It is not a bug, it is a deliberate choice (see [my answer](https://stackoverflow.com/a/64009911/38522)). `NaN !== NaN` is also not a bug (and also nothing to do with JS). – Ben Aston Sep 22 '20 at 15:01
26

What is the difference between null and undefined??

A property when it has no definition, is undefined. null is an object. Its type is object. null is a special value meaning "no value. undefined is not an object, it's type is undefined.

You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". You can even compare a variable that is undefined to null or vice versa, and the condition will be true:

 undefined == null
 null == undefined

Refer to JavaScript Difference between null and undefined for more detail.

and with your new edit yes

if (object == null)  does mean the same  if(!object)

when testing if object is false, they both only meet the condition when testing if false, but not when true

Check here: Javascript gotcha

CodingBarfield
  • 3,332
  • 2
  • 24
  • 52
TStamper
  • 28,864
  • 10
  • 63
  • 72
  • 4
    You should use ===, then undefined !== null :D – olliej Apr 29 '09 at 06:42
  • 1
    pay attention to the last part, is incorrect see my answer ;) – kentaromiura Apr 29 '09 at 07:00
  • 6
    !object is not the same as "object == null" ... In fact, they're quite different. !object will return true if is object is 0, an empty string, Boolean false, undefined or null. – James Apr 29 '09 at 08:38
  • 3
    Is null really an object? The 1st link you have provided checks null by typeof, but typeof(null) evaluates to 'object' because of an language design error. – c4il Sep 01 '10 at 17:21
  • @TStamper: Is the web-site for that 'Javascript gotcha' (http://blog.poundbang.in/post/30056940/javascript-gotcha-undefined-vs-null) taken down? I see a 404 there ... – Everyone Apr 22 '12 at 17:44
  • 3
    `null` is not an object. That `typeof null == 'object';` returns true is because of a bug that can't be fixed in JavaScript (presently, but may change in the future). – Mohamad Dec 30 '14 at 17:51
21

First part of the question:

Why is null considered an object in JavaScript?

It is a JavaScript design error they can't fix now. It should have been type null, not type object, or not have it at all. It necessitates an extra check (sometimes forgotten) when detecting real objects and is source of bugs.

Second part of the question:

Is checking


if (object == null)
Do something

the same as

if (!object)
Do something

The two checks are always both false except for:

  • object is undefined or null: both true.

  • object is primitive, and 0, "", or false: first check false, second true.

If the object is not a primitive, but a real Object, like new Number(0), new String(""), or new Boolean(false), then both checks are false.

So if 'object' is interpreted to mean a real Object then both checks are always the same. If primitives are allowed then the checks are different for 0, "", and false.

In cases like object==null, the unobvious results could be a source of bugs. Use of == is not recommended ever, use === instead.

Third part of the question:

And also:

What is the difference between null and undefined?

In JavaScript, one difference is that null is of type object and undefined is of type undefined.

In JavaScript, null==undefined is true, and considered equal if type is ignored. Why they decided that, but 0, "" and false aren't equal, I don't know. It seems to be an arbitrary opinion.

In JavaScript, null===undefined is not true since the type must be the same in ===.

In reality, null and undefined are identical, since they both represent non-existence. So do 0, and "" for that matter too, and maybe the empty containers [] and {}. So many types of the same nothing are a recipe for bugs. One type or none at all is better. I would try to use as few as possible.

'false', 'true', and '!' are another bag of worms that could be simplified, for example, if(!x) and if(x) alone are sufficient, you don't need true and false.

A declared var x is type undefined if no value is given, but it should be the same as if x was never declared at all. Another bug source is an empty nothing container. So it is best to declare and define it together, like var x=1.

People are going round and round in circles trying to figure out all these various types of nothing, but it's all just the same thing in complicated different clothes. The reality is

undefined===undeclared===null===0===""===[]==={}===nothing

And maybe all should throw exceptions.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Anon
  • 235
  • 2
  • 2
  • 8
    Great answer, but it goes a little too far with []: "_In reality, null and undefined are identical... and maybe the empty containers [] and {}._" You could probably talk me into thinking {} should be some flavor of null, but my gut impression is that it shouldn't. But less controversially, **an empty array `[]` understandably has a `.push()` function**, so there's no good argument for [] being null. $0.02. – ruffin Oct 11 '12 at 20:56
  • Thanks. I feel like this answers the original question better than the chosen answer. I'm hoping can anyone elaborate on "It is a JavaScript design error they can't fix now" and link to docs explaining exactly why javascript acts this way? – Tyson Steele Decker Aug 05 '20 at 21:40
  • It's not a design error (see [my answer](https://stackoverflow.com/a/64009911/38522)). – Ben Aston Sep 22 '20 at 15:03
12
typeof null;      // object
typeof undefined; // undefined

The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.

var x = null;
var y;

x is declared & defined as null

y is declared but not defined. It is declared with no value so it is undefined.

z is not declared so would also be undefined if you attempted to use z.

Chad Grant
  • 40,129
  • 8
  • 59
  • 76
9

One way to make sense of null and undefined is to understand where each occurs.

Expect a null return value in the following situations:

  • Methods that query the DOM

    console.log(window.document.getElementById("nonExistentElement"));
    //Prints: null
    
  • JSON responses received from an Ajax request


    {
      name: "Bob",
      address: null
    }
  • RegEx.exec.

  • New functionality that is in a state of flux. The following returns null:


        var proto = Object.getPrototypeOf(Object.getPrototypeOf({}));

       // But this returns undefined:

        Object.getOwnPropertyDescriptor({}, "a");

All other cases of non-existence are denoted by undefined (as noted by @Axel). Each of the following prints "undefined":

    var uninitalised;
    console.log(uninitalised);

    var obj = {};
    console.log(obj.nonExistent);

    function missingParam(missing){
        console.log(missing);
    }

    missingParam();

    var arr = [];
    console.log(arr.pop());        

Of course if you decide to write var unitialised = null; or return null from a method yourself then you have null occurring in other situations. But that should be pretty obvious.

A third case is when you want to access a variable but you don't even know if it has been declared. For that case use typeof to avoid a reference error:

if(typeof unknown !== "undefined"){
    //use unknown
}

In summary check for null when you are manipulating the DOM, dealing with Ajax, or using certain ECMAScript 5 features. For all other cases it is safe to check for undefined with strict equality:

if(value === undefined){
  // stuff
}
Noel Abrahams
  • 7,213
  • 3
  • 32
  • 34
8

Comparison of many different null checks in JavaScript:

http://jsfiddle.net/aaronhoffman/DdRHB/5/

// Variables to test
var myNull = null;
var myObject = {};
var myStringEmpty = "";
var myStringWhiteSpace = " ";
var myStringHello = "hello";
var myIntZero = 0;
var myIntOne = 1;
var myBoolTrue = true;
var myBoolFalse = false;
var myUndefined;

...trim...

http://aaron-hoffman.blogspot.com/2013/04/javascript-null-checking-undefined-and.html

JavaScript Null Check Comparison Chart

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Aaron Hoffman
  • 5,766
  • 8
  • 53
  • 56
6

To add to the answer of What is the differrence between undefined and null, from JavaScript Definitive Guide 6th Edition, p.41 on this page:

You might consider undefined to represent system-level, unexpected, or error-like absense of value and null to represent program-level, normal, or expected absence of value. If you need to assign one of these values to a variable or property or pass one of these values to a function, null is almost always the right choice.

nonopolarity
  • 130,775
  • 117
  • 415
  • 675
5

null and undefined are both false for value equality (null==undefined): they both collapse to boolean false. They are not the same object (null!==undefined).

undefined is a property of the global object ("window" in browsers), but is a primitive type and not an object itself. It's the default value for uninitialized variables and functions ending without a return statement.

null is an instance of Object. null is used for DOM methods that return collection objects to indicate an empty result, which provides a false value without indicating an error.

Anonymous
  • 42,821
  • 1
  • 23
  • 19
5

Some precisions:

null and undefined are two different values. One is representing the absence of a value for a name and the other is representing the absence of a name.


What happens in an if goes as follows for if( o ):

The expression in the parentheses o is evaluated, and then the if kicks in type-coercing the value of the expression in the parentheses - in our case o.

Falsy (that will get coerced to false) values in JavaScript are: '', null, undefined, 0, and false.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
4

TLDR

undefined is a primitive value in JavaScript that indicates the implicit absence of a value. Uninitialized variables automatically have this value, and functions without an explicit return statement, return undefined.

null is also a primitive value in JavaScript. It indicates the intentional absence of an object value. null in JavaScript was designed to enable interoperability with Java.

typeof null returns "object" because of a peculiarity in the design of the language, stemming from the demand that JavaScript be interoperable with Java. It does not mean null is an instance of an object. It means: given the tree of primitive types in JavaScript, null is part of the "object-type primitive" subtree. This is explained more fully below.

Details

undefined is a primitive value that represents the implicit absence of a value. Note that undefined was not directly accessible until JavaScript 1.3 in 1998. This tells us that null was intended to be the value used by programmers when explicitly indicating the absence of a value. Uninitialized variables automatically have the value undefined. undefined is a one-of-a-kind type in the ECMAScript specification.

null is a primitive value that represents the intentional absence of an object value. null is also a one-of-a-kind type in the ECMAScript specification.

null in JavaScript was designed with a view to enable interoperability with Java, both from a "look" perspective, and from a programatic perspective (eg the LiveConnect Java/JS bridge planned for 1996). Both Brendan Eich and others have since expressed distaste at the inclusion of two "absence of value" values, but in 1995 Eich was under orders to "make [JavaScript] look like Java".

Brendan Eich:

If I didn't have "Make it look like Java" as an order from management, and I had more time (hard to unconfound these two causal factors), then I would have preferred a Self-like "everything's an object" approach: no Boolean, Number, String wrappers. No undefined and null. Sigh.

In order to accommodate Java's concept of null which, due to the strongly-typed nature of Java, can only be assigned to variables typed to a reference type (rather primitives), Eich chose to position the special null value at the top of the object prototype chain (ie. the top of the reference types), and to include the null type as part of the set of "object-type primitives".

The typeof operator was added shortly thereafter in JavaScript 1.1, released on 19th August 1996.

From the V8 blog:

typeof null returns object, and not null, despite null being a type of its own. To understand why, consider that the set of all JavaScript types is divided into two groups:

  1. objects (i.e. the Object type)
  2. primitives (i.e. any non-object value)

As such, null means “no object value”, whereas undefined means “no value”.

enter image description here

Following this line of thought, Brendan Eich designed JavaScript to make typeof return 'object' for all values on the right-hand side, i.e. all objects and null values, in the spirit of Java. That’s why typeof null === 'object' despite the spec having a separate null type.

enter image description here

So Eich designed the heirarchy of primitive types to enable interoperability with Java. This led to him positioning null along with the "object-type primitives" on the heirarchy. To refelct this, when typeof was added to the language shortly thereafter, he chose typeof null to return "object".

The surprise expressed by JavaScript developers at typeof null === "object" is the result of an impedance mismatch (or abstraction leak) between a weakly-typed language (JavaScript) that has both null and undefined, and another, strongly-typed language (Java) that only has null, and in which null is strictly defined to refer to a reference type (not a primitive type).

Note that this is all logical, reasonable and defensible. typeof null === "object" is not a bug, but a second-order effect of having to accommodate Java interoperability.

A number of imperfect backwards rationalisations and/or conventions have emerged, including that undefined indicates implicit absence of a value, and that null indicates intentional absence of a value; or that undefined is the absence of a value, and null is specifically the absence of an object value.

A relevant conversation with Brendan Eich, screenshotted for posterity:

enter image description here

Ben Aston
  • 45,997
  • 54
  • 176
  • 303
  • 1
    yes undefinded means the variable was declared but not initialized to any value or refrence of an object. var x; //now x's value is undefined in practice COMPARE TO var x; x = null; //now x's value is null. Null is just a silly type of object like numbers and strings, which can be used as a placeholder. Undefined means it was not initialized to any value – cmarangu Nov 03 '20 at 19:41
3

null is an object. Its type is null. undefined is not an object; its type is undefined.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Vikas
  • 22,508
  • 34
  • 110
  • 159
  • 11
    wrong - both `null` and `undefined` are primitive values - `typeof null === 'object'` is a language bug, because `Object(null) !== null` – Christoph Apr 29 '09 at 18:16
  • No, is not. Object() cast work in that way, see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf -- 15.2.2.1 new Object ( [ value ] ) ... 8. (The argument value was not supplied or its type was Null or Undefined.) Create a new native ECMAScript object. The [[Prototype]] property of the newly constructed object is set to the Object prototype object. The [[Class]] property of the newly constructed object is set to "Object". The newly constructed object has no [[Value]] property. Return the newly created native object. – kentaromiura Apr 30 '09 at 06:39
  • 3
    @Christoph: I mean, you're right. null *should* be a type, what I means is that you cannot check it in that way because: alert(new Object() !== new Object()); /* true, new istance is not the same istance */ alert(Object(null).constructor == {}.constructor); /* true as in spec */ alert(Object(null).prototype == {}.prototype); /* true as in spec */ alert(null instanceof Object); /* obviously false, null means not instantiated */ But basically is a spec bug XD see: http://www.uselesspickles.com/blog/2006/06/12/javascript-null-identity-crisis/ and http://javascript.crockford.com/remedial.html – kentaromiura Apr 30 '09 at 07:10
2

The following function shows why and is capable for working out the difference:

function test() {
        var myObj = {};
        console.log(myObj.myProperty);
        myObj.myProperty = null;
        console.log(myObj.myProperty);
}

If you call

test();

You're getting

undefined

null

The first console.log(...) tries to get myProperty from myObj while it is not yet defined - so it gets back "undefined". After assigning null to it, the second console.log(...) returns obviously "null" because myProperty exists, but it has the value null assigned to it.

In order to be able to query this difference, JavaScript has null and undefined: While null is - just like in other languages an object, undefined cannot be an object because there is no instance (even not a null instance) available.

Community
  • 1
  • 1
2

In Javascript null is not an object type it is a primitave type.

What is the difference? Undefined refers to a pointer that has not been set. Null refers to the null pointer for example something has manually set a variable to be of type null

AnonDCX
  • 2,121
  • 2
  • 13
  • 23
2

Look at this:

   <script>
function f(a){
  alert(typeof(a));
  if (a==null) alert('null');
  a?alert(true):alert(false);
}
</script>
                                          //return:
<button onclick="f()">nothing</button>    //undefined    null    false
<button onclick="f(null)">null</button>   //object       null    false
<button onclick="f('')">empty</button>    //string               false
<button onclick="f(0)">zero</button>      //number               false
<button onclick="f(1)">int</button>       //number               true
<button onclick="f('x')">str</button>     //string               true
ZPKSoft
  • 31
  • 4
2

For example window.someWeirdProperty is undefined, so

"window.someWeirdProperty === null" evaluates to false while

"window.someWeirdProperty === undefined" evaluates to true.

Moreover checkif if (!o) is not the same as checking if (o == null) for o being false.

Bruce
  • 1,575
  • 4
  • 15
  • 20
Piotr Findeisen
  • 14,631
  • 1
  • 39
  • 67
  • Can you elaborate the difference between the two conditions – rahul Apr 29 '09 at 06:05
  • read my answer, he means that if o is equals to 0, false or "" the Boolean value is false: var undef, various =[0,"",null,false,undef]; for(var obj in various){ alert(!obj); //4 times false in IE,5 in FF ;) } – kentaromiura Apr 29 '09 at 09:55
1

From "The Principles of Object-Oriented Javascript" by Nicholas C. Zakas

But why an object when the type is null? (In fact, this has been acknowledged as an error by TC39, the committee that designs and maintains JavaScript. You could reason that null is an empty object pointer, making "object" a logical return value, but that’s still confusing.)

Zakas, Nicholas C. (2014-02-07). The Principles of Object-Oriented JavaScript (Kindle Locations 226-227). No Starch Press. Kindle Edition.

That said:

var game = null; //typeof(game) is "object"

game.score = 100;//null is not an object, what the heck!?
game instanceof Object; //false, so it's not an instance but it's type is object
//let's make this primitive variable an object;
game = {}; 
typeof(game);//it is an object
game instanceof Object; //true, yay!!!
game.score = 100;

Undefined case:

var score; //at this point 'score' is undefined
typeof(score); //'undefined'
var score.player = "felix"; //'undefined' is not an object
score instanceof Object; //false, oh I already knew that.
Felix
  • 2,910
  • 6
  • 38
  • 52
1

The best way to think about 'null' is to recall how the similar concept is used in databases, where it indicates that a field contains "no value at all."

  • Yes, the item's value is known; it is 'defined.' It has been initialized.
  • The item's value is: "there is no value."

This is a very useful technique for writing programs that are more-easily debugged. An 'undefined' variable might be the result of a bug ... (how would you know?) ... but if the variable contains the value 'null,' you know that "someone, somewhere in this program, set it to 'null.'" Therefore, I suggest that, when you need to get rid of the value of a variable, don't "delete" ... set it to 'null.' The old value will be orphaned and soon will be garbage-collected; the new value is, "there is no value (now)." In both cases, the variable's state is certain: "it obviously, deliberately, got that way."

Mike Robinson
  • 7,537
  • 2
  • 17
  • 28
1

The other fun thing about null, compared to undefined, is that it can be incremented.

x = undefined
x++
y = null
y++
console.log(x) // NaN
console.log(y) // 0

This is useful for setting default numerical values for counters. How many times have you set a variable to -1 in its declaration?

Tim Scollick
  • 1,152
  • 1
  • 13
  • 17
1
  1. Undefined means a variable has been declared but it has not been assigned any value while Null can be assigned to a variable representing "no value".(Null is an assignment operator)

2.Undefined is a type itself while Null is an object.

3.Javascript can itself initialize any unassigned variable to undefined but it can never set value of a variable to null. This has to be done programatically.

the_unknown_spirit
  • 1,988
  • 3
  • 24
  • 47
0

Use null to define something as having no value, use undefined when you expect something might not be defined at all.

For example, if a variable has no value, assign it as null.

var weDontHaveAValue = null;

If you expect that something might be not defined at all, e.g. an optional options argument, use undefined.

if (typeof args.optionalParam !== 'undefined') { }
Maciej Krawczyk
  • 10,012
  • 5
  • 30
  • 38