JavaScriptEasy
What is the difference between null and undefined?
undefined means a value has not been set (the language's default), while null means "intentionally empty" (a value a developer chose to assign).
Where undefined appears automatically
- A declared variable with no value:
let x; - A missing function argument.
- A missing object property or array element.
- A function with no
return.
Where null appears
Only when someone sets it: user.avatar = null, or APIs that return null for "nothing found" (document.querySelector, String.prototype.match, JSON.parse("null")).
Differences that bite
typeof undefinedis"undefined";typeof nullis"object".null == undefinedistrue, butnull === undefinedisfalse.- Default parameters apply for
undefinedonly: passingnullkeepsnull. - JSON:
JSON.stringify({ a: undefined, b: null })gives{"b":null};undefinedproperties are dropped. - Arithmetic:
null + 1is1,undefined + 1isNaN.
Handling both
value ?? fallbackreplaces bothnullandundefined(but not0or"").obj?.propstops safely ifobjis either.value == nullchecks for both in one expression.
Convention
Many teams use undefined for "not provided" and null for "explicitly cleared", and stay consistent.
Code example
js
1let notSet;2const user = { name: "Ada", avatar: null };34console.log(notSet); // undefined5console.log(user.email); // undefined (missing property)6console.log(user.avatar); // null (set on purpose)78console.log(typeof undefined, typeof null); // "undefined" "object"9console.log(null == undefined, null === undefined); // true false1011// Default parameters only replace undefined12const greet = (name = "friend") => `Hi ${name}`;13console.log(greet(undefined), greet(null)); // "Hi friend" "Hi null"1415// JSON drops undefined, keeps null16console.log(JSON.stringify({ a: undefined, b: null })); // {"b":null}1718// Arithmetic19console.log(null + 1, undefined + 1); // 1 NaN2021// Handle both with ?? and ?.22console.log(user.avatar ?? "default.png"); // default.png23console.log(user.settings?.theme ?? "light"); // light
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.