Skip to content

Latest commit

 

History

History
57 lines (38 loc) · 1.93 KB

File metadata and controls

57 lines (38 loc) · 1.93 KB

undefined vs not defined in JS

undefined in JavaScript

Meaning: A variable is declared but has no value assigned.

Happens when:

  • You declare a variable but don't initialize it.
  • A function parameter is missing in a call.
  • You explicitly assign undefined.

Example:

var a;
console.log(a); // undefined

function greet(name) {
  console.log(name);
}
greet(); // undefined

Key Points:

  • undefined is a special value in JavaScript.
  • Declared variables are hoisted and initialized to undefined (in the creation phase).
  • It's a valid value but usually means "no value assigned yet".

not defined in JavaScript

Meaning: The variable has never been declared in the current scope.

Example:

console.log(b); // ReferenceError: b is not defined

Key Points:

  • Accessing an undeclared variable causes a ReferenceError.
  • This happens because the variable doesn't exist in memory at all.

Side-by-Side Comparison

Feature undefined not defined
Declaration ✅ Declared ❌ Never declared
Memory allocation ✅ Yes (value = undefined) ❌ No
Error on access ❌ No error ✅ ReferenceError
Example var a; console.log(a); // undefined console.log(b); // ReferenceError

Interview Soundbite

"undefined means a variable has been declared but not assigned a value, so it's a value and type in JavaScript. not defined means the variable hasn't been declared at all, so accessing it throws a ReferenceError. Variables declared with var are hoisted and initialized to undefined, while accessing undeclared variables immediately causes an error."