Skip to content

JavaScript Error Fixes -- How to Fix Common JS Errors

DodaTech Updated 2026-06-22 5 min read

In this tutorial, you'll learn about JavaScript Error Fixes. We cover key concepts, practical examples, and best practices.

JavaScript errors like TypeError and ReferenceError crash your web app instantly -- this guide shows you how to diagnose and fix the most common JS errors with exact code examples and tested solutions.

What You'll Learn

Why It Matters

JavaScript powers the modern web, and unhandled errors break user interfaces, crash Node servers, and frustrate users. Mastering error debugging makes you a faster, more reliable developer.

Real-World Use

When your React app shows a blank screen or your Express server returns 500 errors, knowing how to read the stack trace and apply the correct fix gets your app back online in minutes.

Common JavaScript Errors Table

Error Message Cause Fix
TypeError: Cannot read property of undefined Accessing a property on an undefined value Check object exists before property access with optional chaining
ReferenceError: x is not defined Variable used without declaration Declare with let, const, or var before use
SyntaxError: Unexpected token Invalid JSON or missing bracket/parenthesis Validate JSON with JSON.parse in try-catch or lint the source
TypeError: x is not a function Calling a non-function value as a function Verify the variable is a function with typeof before calling
RangeError: Maximum call stack size exceeded Infinite recursion or deep recursion Add a base case to recursion or convert to iteration
Uncaught (in promise) TypeError Promise rejection not caught Add .catch() to every promise chain
ReferenceError: Cannot access before initialization Temporal dead zone in let/const Move variable declaration above usage

Step-by-Step Fixes

Fix 1: TypeError -- Cannot Read Property of Undefined

// bad.js
const user = { profile: null };
console.log(user.profile.name);  // TypeError: Cannot read property 'name' of null
// fixed.js
const user = { profile: null };
console.log(user.profile?.name);  // undefined -- safe with optional chaining
// or with fallback
const name = user.profile?.name ?? "Guest";
console.log(name);  // Guest

Expected output:

Guest

Fix 2: ReferenceError -- Variable Not Defined

// bad.js
console.log(counter);  // ReferenceError: counter is not defined
counter = 10;
// fixed.js
let counter = 10;
console.log(counter);  // 10

Expected output:

10

Fix 3: SyntaxError -- Unexpected Token in JSON

// bad.js
const data = '{"name": "Alice", "age": }';
const parsed = JSON.parse(data);
// SyntaxError: Unexpected token } in JSON at position
// fixed.js
const data = '{"name": "Alice", "age": 30}';
try {
    const parsed = JSON.parse(data);
    console.log(parsed.name);  // Alice
} catch (err) {
    console.error("Invalid JSON:", err.message);
}

Expected output:

Alice

Fix 4: Unhandled Promise Rejection

// bad.js
fetch("/api/data")
    .then(res => res.json())
    .then(data => console.log(data));
    // missing .catch() -- promise rejection goes unhandled
// fixed.js
fetch("/api/data")
    .then(res => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
    })
    .then(data => console.log(data))
    .catch(err => console.error("Fetch failed:", err.message));

Expected output:

Fetch failed: HTTP 404

Fix 5: Maximum Call Stack Size Exceeded

// bad.js
function factorial(n) {
    return n * factorial(n - 1);  // no base case
}
console.log(factorial(5));
// RangeError: Maximum call stack size exceeded
// fixed.js
function factorial(n) {
    if (n <= 1) return 1;  // base case stops recursion
    return n * factorial(n - 1);
}
console.log(factorial(5));  // 120

Expected output:

120

Fix 6: Temporal Dead Zone ReferenceError

// bad.js
console.log(name);  // ReferenceError: Cannot access 'name' before initialization
const name = "Alice";
// fixed.js
const name = "Alice";
console.log(name);  // Alice

Expected output:

Alice

JavaScript Error Diagnosis Flowchart

flowchart TD
    A[JS Error Detected] --> B{Error Type?}
    B -->|TypeError| C[Check if object/variable exists]
    C --> D[Add optional chaining or null check]
    B -->|ReferenceError| E[Check if variable is declared]
    E --> F[Declare with let/const before use]
    B -->|SyntaxError| G[Check JSON validity or lint code]
    G --> H[Fix brackets, quotes, or JSON]
    B -->|Promise Rejection| I[Add .catch or try-catch]
    I --> J[Handle error in catch block]
    D --> K[Error Resolved]
    F --> K
    H --> K
    J --> K

Prevention Tips

  • Use optional chaining ?. and nullish coalescing ?? to avoid undefined property access
  • Enable strict mode with "use strict" at the top of every file
  • Run ESLint in your editor to catch reference errors and undefined variables before runtime
  • Always attach .catch() to every promise chain or use async/await with try-catch
  • Validate JSON before parsing with JSON.parse() wrapped in a try-catch block
  • Add base cases to all recursive functions to prevent stack overflow
  • Declare variables at the top of their scope to avoid temporal dead zone issues

Practice Questions

  1. What does TypeError: Cannot read property of undefined mean? Answer: You tried to access a property on a value that is undefined. Use optional chaining ?. or check the value exists first.

  2. How do you prevent unhandled promise rejections in Node.js? Answer: Add a .catch() handler to every promise chain, or use async/await with try-catch blocks around all await calls.

  3. What causes the temporal dead zone in JavaScript? Answer: Using a let or const variable before its declaration line. The variable exists in the scope but cannot be accessed until initialization.

  4. How do you safely parse JSON in JavaScript? Answer: Wrap JSON.parse() in a try-catch block so malformed JSON throws an error you can handle instead of crashing the program.

  5. Challenge: Write an async function that fetches data from an API, handles network errors with a retry mechanism (up to 3 retries), and returns a default fallback value if all retries fail. Answer:

    async function fetchWithRetry(url, retries = 3) {
        for (let i = 0; i < retries; i++) {
            try {
                const res = await fetch(url);
                if (!res.ok) throw new Error(`HTTP ${res.status}`);
                return await res.json();
            } catch (err) {
                if (i === retries - 1) return { error: "Fallback data" };
                await new Promise(r => setTimeout(r, 1000 * (i + 1)));
            }
        }
    }
    

Quick Reference

Error Cause Quick Fix
TypeError: undefined property Accessing null/undefined Use ?. or ?? operators
ReferenceError: not defined Missing variable declaration Add let, const, or var
SyntaxError: unexpected token Invalid JSON or syntax Enable linter and validate JSON
Promise rejection unhandled Missing .catch() Add try-catch or .catch() handler
RangeError: stack overflow Infinite recursion Add base case to recursive function
TDZ ReferenceError Using let/const too early Declare before use in same scope

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro