How do you check whether a JavaScript variable is null or undefined?
The simplest and cleanest way to check whether a JavaScript variable is null or undefined is using value == null. In JavaScript, == null is a safe rule that checks for both null and undefined at once while ignoring other falsy values like 0, “” (empty string), or false.
Understanding null, undefined, and typeof Clearly
undefined usually means a variable has been created or a property is missing, while null is a value you intentionally assign to show “nothing” or “empty.” Even though people normally avoid == in JavaScript, value == null is a famous exception that only matches null and undefined. If a variable might not even be declared in your code yet, typeof missingVar === “undefined” checks it safely without throwing a ReferenceError.
JavaScript
let studentName; // undefined (no value assigned yet)
let middleName = null; // null (intentionally empty)
let points = 0; // 0 (falsy number, not null/undefined)
let label = ""; // "" (falsy string, not null/undefined)
console.log(studentName == null); // true
console.log(middleName == null); // true
console.log(points == null); // false
console.log(label == null); // false
// Strict alternative for declared variables
console.log(studentName === null || studentName === undefined); // true
// Safe check when a variable might not be declared at all
console.log(typeof notDeclaredYet === "undefined"); // true
You must log in or register to comment.
