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.