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
?
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
?
In Javascript
null
is not anobject
type it is aprimitave
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
The difference can be summarized into this snippet:
Checking
object == null
is different to checkif ( !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:
Look at this:
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
JSON responses received from an Ajax request
RegEx.exec.
New functionality that is in a state of flux. The following returns null:
All other cases of non-existence are denoted by undefined (as noted by @Axel). Each of the following prints "undefined":
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:
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:
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:
Refer to JavaScript Difference between null and undefined for more detail.
and with your new edit yes
when testing if object is false, they both only meet the condition when testing if false, but not when true
Check here: Javascript gotcha
x is defined as null
y is not defined; // because I did not define it
null is evaluated as false