JavaScript undefined vs not defined: Debugging errors in code

Day 30/50 – JavaScript Interview Question? Question: What is the difference between undefined and not defined? Simple Answer: undefined is a primitive value assigned to declared variables that haven't been initialized, or returned by functions with no return value. "not defined" means the variable was never declared at all, resulting in a ReferenceError. 🧠 Why it matters in real projects: Understanding this distinction helps debug errors faster. undefined is a valid value that can be intentionally assigned, while "not defined" indicates a typo, missing import, or scope issue. This affects type checking and error handling strategies. 💡 One common mistake: Checking for undefined incorrectly using if (x) which also catches null, 0, false, and empty strings. Use strict equality x === undefined or typeof x === 'undefined' for precise checks. 📌 Bonus: // undefined - declared but not initialized let x; console.log(x); // undefined console.log(typeof x); // "undefined" // not defined - never declared console.log(y); // ReferenceError: y is not defined // Function with no return function test() { // no return statement } console.log(test()); // undefined // Explicit undefined assignment let user = undefined; // Valid but unusual // Proper checking for undefined let value; // ✗ Imprecise - catches other falsy values if (value) { } // ✓ Precise checking if (value === undefined) { } if (typeof value === 'undefined') { } // Safe even if not declared // Optional chaining for nested undefined const name = user?.profile?.name; // undefined if any step is undefined // Nullish coalescing - only null/undefined const display = value ?? 'default'; // Not triggered by 0 or '' // Default parameters function greet(name = 'Guest') { // Only uses default if undefined console.log(`Hello, ${name}`); } greet(); // "Hello, Guest" greet(undefined); // "Hello, Guest" greet(null); // "Hello, null" - null is a value! #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #Undefined #WebDev #InterviewPrep #Debugging

To view or add a comment, sign in

Explore content categories