#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
3 min read
Question 23 of 50easy

What is the difference between null and undefined?

Understanding null and undefined values.

What You'll Learn

  • Difference between null and undefined
  • When each is used
  • Checking for both

Comparison

Aspectundefinednull
Typeundefinedobject
MeaningNot assignedIntentionally empty
DefaultVariable declarationMust be assigned

Examples

code.jsJavaScript
// undefined - automatically assigned
let x;
console.log(x); // undefined

function test(a) {
  console.log(a); // undefined if not passed
}

const obj = {};
console.log(obj.prop); // undefined

// null - intentionally assigned
let y = null;

function findUser(id) {
  // Return null if not found
  return users.find(u => u.id === id) || null;
}

Type Checking

code.jsJavaScript
typeof undefined // 'undefined'
typeof null      // 'object' (historical bug)

// Equality
null == undefined  // true
null === undefined // false

// Check for both
if (value == null) {
  // Catches both null and undefined
}

// Modern approach
value ?? 'default' // Nullish coalescing

Nullish Coalescing (??)

code.jsJavaScript
const a = null ?? 'default';    // 'default'
const b = undefined ?? 'default'; // 'default'
const c = 0 ?? 'default';       // 0
const d = '' ?? 'default';      // ''