JavaScript is a dynamically typed language, which means that variables can contain values of any type without checking for type. While this flexibility is useful, it can also cause confusion and errors, particularly when working with null and undefined values. Both null and undefined indicate the lack of a value, yet they are used in distinct scenarios. In this post, we'll look at the differences between null and undefined, common instances in which they appear, and recommended practices for dealing with them in your code.
Before going into checking methods, it's important to understand the fundamental distinction between null and undefined:
In JavaScript, undefined is a primitive value which signifies the absence of a value. It is automatically given to variables that were declared but not initialized. However, there are other instances in which undefined can arise, making it a critical subject to understand well.
let x; console.log(x); // Output: undefined
const obj = {}; console.log(obj.nonExistentProperty); // Output: undefined
function doSomething() { // No return statement } console.log(doSomething()); // Output: undefined
const arr = [1, 2, 3]; console.log(arr[5]); // Output: undefined
function greet(name) { console.log(name); } greet(); // Output: undefined
console.log(void 0); // Output: undefined
const user = { name: "Alice" }; delete user.name; console.log(user.name); // Output: undefined
let b = undefined; console.log(b); // Output: undefined
Null is another primitive value in JavaScript, however unlike undefined, it requires explicit assignment. It denotes the purposeful absence of any object value. Null is utilized in a variety of contexts, therefore it is a conscious programming choice.
let x = null; console.log(x); // Output: null
let data = { key: "value" }; data = null; // Clear the variable console.log(data); // Output: null
const user = { name: "Alice", parent: null // No parent relationship }; console.log(user.parent); // Output: null
const response = { data: null, // Data not yet available error: null // No error occurred };
const element = document.querySelector(".non-existent-class"); console.log(element); // Output: null
const jsonData = JSON.stringify({ key: null }); console.log(jsonData); // Output: "{\"key\":null}"
function createUser(name, age, address = null) { return { name, age, address }; } console.log(createUser("Alice", 25)); // Output: { name: "Alice", age: 25, address: null }
In terms of type:
console.log(typeof undefined); // Output: "undefined" console.log(typeof null); // Output: "object"
In JavaScript, null and undefined are loosely equivalent (==), but not to any other value. However, they are not strictly equivalent (===) to one other.
console.log(null == undefined); // Output: true console.log(null === undefined); // Output: false
To check if a variable is either null or undefined, you can use the following:
if (x == null) { // x is either null or undefined }
The typeof operator can be used to determine whether a variable is undefined.
if (typeof x === 'undefined') { // x is undefined }
However, since typeof null returns "object", it cannot be used to distinguished between null and other objects.
To explicitly check for null or undefined values, use strict equality (===).
if (x === null) { // x is null } if (x === undefined) { // x is undefined }
Modern JavaScript allows you to safely access deeply nested properties without explicitly checking if each reference in the chain is null or undefined—optional chaining.
const user = { address: { city: "New York" } }; console.log(user.address?.city); // Output: New York console.log(user.contact?.phone); // Output: undefined
When its left-hand side operand is null or undefined, the nullish coalescing operator (??) is a logical operator returning its right-hand side operand.
const x = null; const y = x ?? 'default'; console.log(y); // Output: default
let x = null; // Explicitly set to null
function greet(name = 'Guest') { console.log(`Hello, ${name}`); } greet(); // Output: Hello, Guest
const user = { address: { city: "New York" } }; console.log(user.address?.city); // Output: New York
const x = null; const y = x ?? 'default'; console.log(y); // Output: default
if (x === null || x === undefined) { // x is either null or undefined }
At DevelopersMonk, we share tutorials, tips, and insights on modern programming frameworks like React, Next.js, Spring Boot, and more. Join us on our journey to simplify coding and empower developers worldwide!