I have been using JavaScript for couple of years and never cared about the difference between null & undefined earlier, I always use undefined to validate the object existence.
But recently I came through this article. Here they said
JavaScript distinguishes between null, which is an object of type ‘object’ that indicates a deliberate non-value, and undefined, which is an object of type ‘undefined’ that indicates an uninitialized value — that is, a value hasn’t even been assigned yet. We’ll talk about variables later, but in JavaScript it is possible to declare a variable without assigning a value to it. If you do this, the variable’s type is undefined.
I am completely confused now, what exactly is non-value here. How this non-value differs from undefined. And what are the circumstances javascript returns null.
I have tried the below sample
var sam;
alert(sam); // returns undefined
And
try {
//var sam;
alert(sam);
} catch(ex) { } // exception says: sam is undefined
And I am not sure about when js returning nulls. Can someone clarify me.
Nope, that’s an exception.
You get
undefinedwhen you access an unset property; you get an error when you use an unset name directly.Global variables are interesting because they can be accessed either using a simple variable name, or by using properties of the
windowglobal object:If
samis declared but not initialised, accessingwindow.samstill gets youundefined, but for a different reason: there is an entry in thewindowobject forsam, but it points to the sameundefinedobject as you get when you access a non-existant property.This is of course a confusing bloody mess;
undefinedis one of the worst mistakes in the design of the JavaScript language.nullon the other hand is fine and works pretty much the same as null/nil/void/None values in other languages. It doesn’t come into any of the above.