ā¤ Like
šŸ”– Save
šŸ”— Share
@thedevspaceio
@thedevspaceio

JavaScript null vs undefined

@thedevspaceio

ā“ JavaScript null vs undefined Cheatsheet

null and undefined both represent empty values, but they mean different things and behave differently in logical comparisons and type checks.

āœ… undefined āœ… null āœ… Differences āœ… typeof behavior āœ… Checking for empty values āœ… Nullish coalescing

#javascript #null #undefined #types #comparison #webdev #frontend #coding #tips


JavaScript comes with two values that means "no value": undefined and null.

undefined means a variable has been declared but has not been assigned a value.

null, on the other hand, is an intentional absence of value assigned by the developer.


undefined

undefined is the default value for uninitialized variables, missing function arguments, and object properties that do not exist.

js
let name;
console.log(name); // undefined
js
function greet(message) {
  console.log(message);
}
greet(); // undefined
js
const user = {};
console.log(user.age); // undefined

null

null represents a deliberate "no value". It is often used to clear a variable or indicate that an object reference is intentionally empty.

js
let user = { name: "Ada" };
user = null; // intentionally cleared
 
console.log(user); // null

Key differences

Aspectundefinednull
MeaningValue not assignedIntentional absence of value
Type"undefined""object" (legacy bug)
DefaultGiven by JavaScriptAssigned by developer
== comparisonundefined == null is truenull == undefined is true
=== comparisonundefined === null is falsenull === undefined is false

typeof behavior

js
typeof undefined; // "undefined"
typeof null; // "object" (a legacy JavaScript quirk)

To check for null, use strict equality.

js
const value = null;
value === null; // true

Checking for empty values

Use strict equality when you need to distinguish between null and undefined.

js
const a = null;
const b = undefined;
 
a === null; // true
b === undefined; // true
a === b; // false

Use loose equality when either value should be treated as empty.

js
const value = null;
 
if (value == null) {
  console.log("value is null or undefined");
}

Nullish coalescing

The ?? operator treats only null and undefined as missing values.

It returns the right-hand side if the left-hand side is null or undefined, otherwise it returns the left-hand side.

js
const count = 0;
console.log(count ?? 10); // 0
 
const name = null;
console.log(name ?? "Anonymous"); // "Anonymous"

Full-Stack AI Developer Roadmap

From HTML & CSS to working with AI models, all in one structured roadmap.

@thedevspaceio
www.thedevspace.io