Undefined / Null
Explore the concepts of undefined and null in JavaScript to understand how variables behave when not assigned values or intentionally set to be empty. Learn when and why to use these types as part of mastering basic data handling in JavaScript.
We'll cover the following...
Undefined values
When you declare a variable, its value is initialized to whatever value you assign by using the = sign. The following code snippet will initialize the variable as pi a number.
But what if we created a variable that didn’t assign any value, like so?
Does the variable still exist? Turns out, it does.
declaredValue, in this case, is a declared variable with an undefined value. It is also the case that declaredValue is of type undefined. An undefined type is given to any variable that has not been assigned a value, or if a variable doesn’t exist at all.
Null values #
Variables with a null type, on the other hand, represent values that are intentionally empty. A null variable can be created by setting the variable equal to null.
Undefined vs. null
Variables are only stored as undefined if they have been declared but not instantiated with a value. Null values intentionally are stored as null to indicate that the variable is empty. You should set a variable equal to null if and only if the variable is expected to have no value.
If this isn’t making sense right now, it’s alright! We will continue to touch on this concept in subsequent lessons.