Why is null an object and what's the difference between null and undefined?
Solution 1
(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.
Solution 2
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
Solution 3
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
Solution 4
What is the difference between null and undefined??
A property when it has no definition is undefined
. a null
is an object. Its type is object
. null is a special value meaning "no value. undefined is not an object, its 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
Solution 5
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.
rahul
Updated on January 03, 2022Comments
-
rahul over 2 years
Why is
null
considered anobject
in JavaScript?Is checking
if ( object == null ) Do something
the same as
if ( !object ) Do something
?
And also:
What is the difference between
null
andundefined
? -
olliej about 15 yearsYou should use ===, then undefined !== null :D
-
please delete me about 15 yearspay attention to the last part, is incorrect see my answer ;)
-
James about 15 years!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.
-
please delete me about 15 yearsread 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 ;) }
-
Christoph about 15 yearswrong - both
null
andundefined
are primitive values -typeof null === 'object'
is a language bug, becauseObject(null) !== null
-
please delete me about 15 yearsNo, is not. Object() cast work in that way, see 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.
-
please delete me about 15 years@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: uselesspickles.com/blog/2006/06/12/… and javascript.crockford.com/remedial.html
-
Andreas Grech about 14 yearsBut in JavaScript, the empty string '' is still a boolean false.
-
c4il over 13 yearsIs 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.
-
Bryan Matthews over 13 yearsThe empty string is not boolean false, but in the context of a conditional it is interpreted as a false(y) value (coercion).
-
Jean Vincent almost 13 yearsFor 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.
-
mikl almost 13 yearsRather 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. -
Raynos over 12 yearsWhy reference
+0
and-0
seperately if+0 === -0
? -
MC Emperor over 12 yearsLove 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 inundefined
. -
jinglesthula over 12 years@MC Emperor - also, you can explicitly set a declared variable to
undefined
, so I agree that the "You haven't ever mentioned anyname
before" is a bit misleading. -
Pakman about 12 yearsThis doesn't answer the question of: "Is (object == null) the same as (!object)"
-
Churk about 12 yearsI always thought undefined was same as a null. But now I realized undefined is almost like null of a null.
-
Everyone about 12 years@TStamper: Is the web-site for that 'Javascript gotcha' (blog.poundbang.in/post/30056940/…) taken down? I see a 404 there ...
-
xr280xr almost 12 years@kentaromiura For us Javascript noobs...maybe only me...what is this Boolean(value) syntax? Casting to a Boolean?
-
ruffin over 11 yearsGreat 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. -
Tim van Dalen over 11 years>Are you seeing some other scripting language on the (client-)side? Hahahaha
-
squidbe over 11 years@xr280xr Yes, it's casting. Try
String(null)
to see another example of casting. You can even do silly things likeNumber(null + 2)
... but you shouldn't :-). Excellent answer from kentaromiura. -
squidbe over 11 years@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) whereasvar 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. -
gmajivu almost 11 yearsTested 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 sincetypeof(name) = 'string'
. The variablename
is implicitly a string. What a subtlety! -
alphakevin almost 11 years@AndreasGrech: [false] is not actually [""], if you put === between the two
-
Andreas Grech almost 11 years@antmary Indeed, and that's because
===
does not do type coercion. -
Tiddo almost 11 yearsI 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. -
neo almost 11 yearsProbably because you can still distinguish
+0
and-0
:1/+0 !== 1/-0
. -
Zlatko over 10 years@AndreasGrech In Javascript, the empty string is not a Boolean false. It simply evaluates to Boolean false when you use coercion.
-
Ricardo Tomasi over 10 yearsThis answer links to a post that links back to this answer as source... probably meant to link to this instead 2ality.com/2013/10/typeof-null.html
-
Mohamad over 9 years
null
is not an object. Thattypeof null == 'object';
returns true is because of a bug that can't be fixed in JavaScript (presently, but may change in the future). -
Qi Fan about 9 yearsdoes "var myUndefined;" define the variable (as a known variable with unknown type)?
-
user3167101 over 8 yearsRemember
typeof
is an operator. You wouldn't wrap the operand in parenthesis for the same reason you wouldn't writevar sum = 1 +(1);
. -
samus over 8 yearsOh right, like in C, where uninitialized variable declarations are considered undefined (old versions could actually contain a previous programs data).
-
Oriol almost 8 yearsProgrammers can also use
undefined
to indicate "no value", and JS can also usenull
to indicate "no value". -
luigi7up over 7 yearsLove the story telling approach :D
-
Bekim Bacaj over 7 years@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.
-
Costa Michailidis over 7 yearstypeof 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. -
Gajus over 7 years"But that is actually a bug (that might even be fixed in ECMAScript 6)" – source?
-
Matt S almost 7 yearsI would like to agree with Tiddo and suggest that the cause of a value being
undefined
is ambiguous whereasnull
is like saying "this space intentionally left blank". -
jchook over 6 yearsI think @neo is the one.
-
Nina Scholz over 5 years
name
is a part protected (it can be only a string) property of window. -
Armen Michaeli over 5 yearsThere is no
is
keyword in JavaScript/ECMAScript, much less an operator, is it? I am referring to the(name is undefined)
expression. -
Christian Vincenzo Traina about 5 yearsIt won't ever be fixed. If it gets fixed all the internet could break down. It's the same problem of NaN === NaN
-
Tyson Steele Decker almost 4 yearsThanks. 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?
-
Ben Aston over 3 yearsIt is not a bug, it is a deliberate choice (see my answer).
NaN !== NaN
is also not a bug (and also nothing to do with JS). -
Ben Aston over 3 yearsIt's not a design error (see my answer).
-
Ben Aston over 3 yearsThis answer is misleading to the point of being incorrect. I have written a referenced answer below.
-
Ben Aston over 3 years
null
is not an instance ofObject
. -
Ben Aston over 3 yearsThis answer conflates undeclared with
undefined
. -
cmarangu over 3 yearsyes 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
-
Alexandre Piva almost 3 years@AndreasGrech In refer to this: No, it is not. It is falsy, but not boolean.
-
IT goldman almost 2 yearsnull should have never been an object