One thing that threw me off when I started learning JavaScript (with a background in Java) was the fact that JavaScript has both undefined
and null
as possible values for a variable.
In Java, all we have is just null
which means that the variable has no value.
So when I saw this additional value of undefined
in JavaScript, I was confused… what did it mean?
Undefined Means “Nothing”
When a variable has the value of undefined
it means two things:
- A variable has been declared
- The variable that has been declared has not yet been assigned ANY value whatsoever
An example of this in JavaScript would be as follows:
var person;
So as you can see, I've declared a variable, but I haven't assigned a value.
Now if I were to inspect that person
variable to see what value it contained, you'd see that it says “undefined”.
var person; alert("The person variable has the value: " + person);
Here's what the output of this code would be:
Now it's also interesting to note that when we inspect the type that is assigned to our person
variable, we'll get the type undefined
. This makes sense if you remember reading this article on the different data types in JavaScript.
Okay, fair enough then right?
undefined
means that there's nothing assigned to our variable… so then, what the heck does null
mean?
Null is a Place-holder for Nothing
In JavaScript null
means that you've intentionally assigned a value to your variable, and therefore you're intentionally assigning the value of nothing to your variable.
You can think null
like a place-holder, meaning that the variable has nothing inside of it, but you intend on assigning it a value later.
The interesting thing to note about assigning null
to a variable is what type JavaScript gives to a variable that has been assigned the value of null
. Let's take a look:
var person = null; alert("The person variable has the data type: " + (typeof person));
Here's the result:
What!?
The type of our person
variable is object
?
Believe it or not, this is a bug in JavaScript that they've just sort of “leaned into” and stuck with over the years. It's part of the way the JavaScript engine works and if they changed it now, it would likely cause some side-effects to a lot of code out there on the interwebs.
The common justification for this bug is that when you're using the value of null
for a variable, it's because you're using it as a place-holder for an object
that will be assigned to this variable later.
Not the greatest justification, but that's just how the cookie crumbles in this case.
In Summary
The value of undefined
is assigned to any variable that has not yet been assigned a value.
The value of null
can be assigned by YOU if you like, and it represents a lack of a value (aka. nothing!)
Clear as mud?
Good!
No go and put your email address into the box below so I can send you a free goodie that you'll love. You've already read down to the bottom of this article, so I know you'll love the stuff I'll send to you.
Boo yah!