Skip to content

Null vs Undefined

JavaScript has two values that mean “no value”. undefined is what the language gives you when nothing has been assigned, and null is what a programmer assigns to say, on purpose, that there is nothing there.

JavaScript produces undefined by itself in several places: a variable declared without a value, a property that the object does not have, and the result of a function that has no return statement.

let discountCode;
const basket = { apples: 3 };
function addItem(name) {
// no return statement
}
console.log(discountCode);
console.log(basket.pears);
console.log(addItem('pears'));

This prints:

undefined
undefined
undefined

A missing argument is also undefined inside the function, and so is an array element past the end of the array.

null does not appear unless some code puts it there. It is the usual way to record that a value is known to be empty, which is different from a value that was never set.

const user = { name: 'Priya', manager: null };
console.log(user.manager);
console.log(user.phone);
console.log('manager' in user, 'phone' in user);

This prints:

null
undefined
true false

The user has a manager property whose value is deliberately empty, but has no phone property at all.

typeof null returns 'object', which is a mistake from the first version of JavaScript that was kept so that old code would not break. null is a primitive value, not an object.

Strict equality treats the two as different values, while loose equality treats them as equal to each other and to nothing else.

console.log(typeof undefined);
console.log(typeof null);
console.log(null === undefined);
console.log(null == undefined);
console.log(null == 0, undefined == 0);

This prints:

undefined
object
false
true
false false

So value == null is a short way to test for either one, and it is the one place where many style guides accept ==. See Double vs Triple Equals for the general rule. Both values are also falsy, so !null and !undefined are both true.

Converted to a number, null becomes 0 and undefined becomes NaN. JSON.stringify keeps a property whose value is null but drops one whose value is undefined.

console.log(5 + null);
console.log(5 + undefined);
console.log(JSON.stringify({ due: null, notes: undefined }));

This prints:

5
NaN
{"due":null}

Default parameters apply only when the argument is undefined, so passing null skips the default. The nullish coalescing operator ?? and optional chaining ?. treat the two values the same way.

function greet(name = 'guest') {
return `Hello, ${name}`;
}
console.log(greet(undefined));
console.log(greet(null));
const settings = { pageSize: null };
console.log(settings.pageSize ?? 20);

This prints:

Hello, guest
Hello, null
20

A common convention follows from this: leave undefined to the language, and use null in your own code whenever you mean “deliberately empty”.

Steve Griffith covers this topic in his video JavaScript null vs. undefined.