When something doesn't exist
In JavaScript, we have two ways to say that something doesn't exist. These are the keywords null
and undefined
. These keywords are a nightmare for some, but if you master them, you'll be fine.
Both means that there is no value there, and if you try to see if they are equal... Well, here's an example:
So that's fine, they both represent "nothing". But are they of the same data type?
They are not. We can use the unary operator `typeof` to find out what they really are.
undefined
means a variable has been declared but has not yet been assigned a value. null
is an assignment value, and can be assigned to a variable. More often than not they can be used interchangeable. If you try to print the value of a variable that doesn't have a value, you will get undefined
in return. You can also declare a variable with the value of undefined
or null
if you need to assign it a value later. This can often lead to errors though, i.e. if you think it has a value and it doesn't, so use it with care.
If you need to use a variable that at some point have been undefined
or null
, it might be a good idea to check for it. Check for it how? Well, that's a perfect segue to the next section!
Last updated
Was this helpful?