There are two more primitive value types. They have similar interpretations in JavaScript but they mean different things.
null is used to show there is purposely no value for a variable
undefined means a variable type was never specified
In JavaScript, both null and undefined are evaluated as false.
If you purposely want something to not have a value, set it to null. This will help you identify other problems if they arise.
One day, you make plans to hang out with your friends, but you haven't figured out what to do yet, so the plans are up in the air. These plans would be considered undefined. You don't know what kind of plans you're going to make. Will you go bowling? Go to a movie? Play video games? Go to the mall? Grab lunch? Go skydiving? Write a novel? It could be anything!
Let's say you're playing a game of bowling with two friends. Each friend has a name saved in a variable. At the end of the game, one friend is going to leave and maybe come back. You would set their name variable to null because, for a while, there is no playing in that spot.
In this sort of silly example, there is a big difference between null and undefined. Can you spot the difference?
We set null when the function recognizes our friend who isn't going to play, so it leaves the spot open. But when the stranger shows up, the function doesn't recognize who it is, so it sends back undefined, even though the stranger is still going to play with us.
In situation 1, we purposely set player2
to an empty value (null) when
Kevin was on the phone.
In sitatuon 2, the function didn't know what to do so it sent nothing back (undefined). We can check the difference between null and undefined, so we can test to make sure the function is working properly later.
If we want the computer to test to see if there is a player2
currently in the game, we'd want to check
it carefully. If we just do a basic true/false test, such as if (player2)
,
we would get false in both situations. This isn't accurate. In situation 1 this
comparison would be correct because no one was playing as player2
while Kevin was on the phone. But
this check fails in situation 2 because we actually do have someone as player2
, but the
function just didn't know what to do with the stranger it didn't recognize.
I have found that undefined comes up a lot on its own when there are bugs in the code. For example, if you call a function that's supposed to take a parameter but you don't send one, the parameter is set to undefined. Also, if a function doesn't return a value, it defaults to returning undefined.
However, if you purposely know that you wanted something cleared out, then you should set it to null. The computer can automatically assign undefined, but you have to set null. This allows you to check to make sure things are working as you planned.