Null object in javascript

up vote 209 down vote favorite
99

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?

javascript object null
share|improve this question
edited Apr 26 '11 at 13:40
spacer
Simon Nickerson
11.7k23672
asked Apr 29 '09 at 5:47
spacer
rahul
52k967111

75% accept rate
feedback

12 Answers

active oldest votes
up vote 499 down vote accepted
(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

share|improve this answer
answered Apr 29 '09 at 13:31
spacer
Rob
21.1k12656
6  
But in JavaScript, the empty string '' is still a boolean false. – Andreas Grech Feb 21 '10 at 21:11
145  
what a funny way to explain – Jake Apr 29 '10 at 21:33
14  
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
6  
I love your banter. – James Andino May 21 '11 at 18:42
11  
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
show 7 more comments
feedback
up vote 58 down vote

The difference can be summarize 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 equals 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

bye ;)

share|improve this answer
edited Apr 29 '09 at 7:25

answered Apr 29 '09 at 6:44
spacer
kentaromiura
1,716812
2  
+1, for the explanation of !Boolean(object) – c4il Sep 1 '10 at 17:14
@kentaromiura For us Javascript noobs...maybe only me...what is this Boolean(value) syntax? Casting to a Boolean? – xr280xr Jun 12 at 20:37
feedback
up vote 18 down vote

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
share|improve this answer
edited Nov 7 '11 at 2:56

answered Nov 1 '11 at 15:06
spacer
Axel Rauschmayer
56147
Why reference +0 and -0 seperately if +0 === -0 ? – Raynos Nov 7 '11 at 3:09
feedback
up vote 15 down vote

What is the difference between null and undefined??

A property when it has no definition, is undefined. null is an object. It's type is null. 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

share|improve this answer
edited Apr 29 '09 at 22:03

answered Apr 29 '09 at 5:52
spacer
TStamper
11.5k22757
edited my post for the condition checking – rahul Apr 29 '09 at 5:54
2  
You should use ===, then undefined !== null :D – olliej Apr 29 '09 at 6:42
pay attention to the last part, is incorrect see my answer ;) – kentaromiura Apr 29 '09 at 7:00
2  
!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. – 999 Apr 29 '09 at 8:38
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 1 '10 at 17:21
show 1 more comment
feedback
up vote 11 down vote
Question first part:

Why is null considered an object in javascript?

Javascript design error they can't fix now. Should have been type null not type object, or not have it at all. Necessitates an extra check (sometimes forgotten) when detecting real objects. Source of bugs.

Question second part:

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 object is not 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 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.

Question 3rd part:

And also

What is the difference between null and undefined?

In Javascript, one difference is that null is type object and undefined is 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 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, e.g. 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 should be the same as if x was never declared at all. Another bug source empty nothing container. So best to declare and define 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.

share|improve this answer
answered Jul 14 '11 at 22:15
spacer
Anon
11112
1  
+1 for that statement at the end. – dmackerman Sep 9 '11 at 20:44
+1 for answering ALL the questions – Pakman Mar 14 at 16:33
feedback
up vote 7 down vote
var x = null;

x is defined as null

y is not defined; // because I did not define it

if (!x)

null is evaluated as false

share|improve this answer
answered Apr 29 '09 at 5:56
spacer
Chad Grant
11k2437
feedback
up vote 5 down vote

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.

share|improve this answer
answered Apr 29 '09 at 5:58
spacer
Anonymous
3,8831812
feedback
up vote 4 down vote

null is an object. It's type is null. undefined is not an object, it's type is undefined.

share|improve this answer
answered Apr 29 '09 at 5:51
spacer
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.