Categories
JavaScript Programming

Undefined vs Null in JavaScript

To myself… May I help other fellow coders use undefined and null appropriately through this short article.

Variable declaration and initialisation

Before having a solid understanding of the differences between undefined and null, it’s important to know the steps in declaring and initialising a variable.

Declaring is giving the variable a name.

let catName;

Initialising is giving the variable a value

catName = "Felicia";

Combining these two statements, we have a variable that has been declared with a name catName and a value of Felicia

let catName; // declaration
catName = "Felicia"; // initialisation

Undefined

Technically speaking, undefined means lack of an assigned value.

You can think of undefined as the default value of variable when it has not been assigned a value.

Rephrased slightly, undefined means either (1) variable is not declared (2) variable is declared but no value is assigned to it.

Null

With null, it means variable is declared and the coder explicitly set the value to null.

Null can be used to mean that the value does exist but at this point it is not yet known. For example an online form with an age field. Setting the age variable with null value means we know that the person’s age exists but we don’t know it yet (since the person has not filled in the details yet).

Difference in data types

The undefined is in its own data type whereas null is an object. Pretty confusing but that’s how undefined and null are designed in JavaScript.

Something to think about

Typically, you can lose the context between the JavaScript language assigning the variable a value and you as a coder explicitly assigning the variable a value. Hence, if you need to assign an emptiness to the variable, null is used. If it’s the JavaScript to assign the value, you just need to declare the variable and it will have implicit default value of undefined.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s