Null vs Undefined in JavaScript

Olivier Trinh
2 min readSep 14, 2023

--

Null and undefined are two special values in JavaScript that represent the absence of a value. They are often confused with each other, but there are some important differences between them.

Undefined

Undefined is a value that is assigned to a variable that has not been given a value yet. For example, the following code will create a variable called name and assign it the value of undefined:

var name;

The name variable is now undefined, which means that it does not have any value. If you try to print the value of name, you will get undefined.

Null

Null is a value that is assigned to a variable that is intentionally set to have no value. For example, the following code will create a variable called age and assign it the value of null:

var age = null;

The age variable is now null, which means that it does not have any value. However, it is different from undefined in that it is a deliberate choice to set the value to null.

Null and undefined are often used in JavaScript to represent the absence of a value. For example, you might use null to represent a missing value in a database, or you might use undefined to represent a variable that has not been initialized yet.

It is important to use null and undefined correctly in your JavaScript code. Using them incorrectly can lead to errors and unexpected behavior.

Here are some examples of how null and undefined can be used in JavaScript:

// Undefined
var name;
console.log(name); // undefined

// Null
var age = null;
console.log(age); // null

// Checking for null or undefined
var value = null;
if (value === null || value === undefined) {
console.log("The value is null or undefined.");
}

--

--