JsGuide

Learn JavaScript with practical tutorials and code examples

errorsbeginner10 min read

Common JavaScript Errors and How to Fix Them

Learn to identify and fix the most common JavaScript errors. From syntax errors to runtime exceptions, master debugging techniques with practical examples.

By JSGuide Team

Common JavaScript Errors and How to Fix Them

JavaScript errors can be frustrating, but understanding common patterns helps you debug faster and write more reliable code. Let's explore the most frequent JavaScript errors and their solutions.

1. ReferenceError: Variable is not defined #

This occurs when you try to use a variable that hasn't been declared.

❌ Common Mistake #

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

✅ Solution #

// Declare the variable first
let userName = "Alice";
console.log(userName); // Output: Alice

// Or check if variable exists
if (typeof userName !== 'undefined') {
    console.log(userName);
} else {
    console.log('userName is not defined');
}

2. TypeError: Cannot read property of undefined/null #

This happens when you try to access a property on undefined or null.

❌ Common Mistake #

let user = null;
console.log(user.name); // TypeError: Cannot read property 'name' of null

let data;
console.log(data.length); // TypeError: Cannot read property 'length' of undefined

✅ Solution #

let user = null;

// Solution 1: Check before accessing
if (user && user.name) {
    console.log(user.name);
} else {
    console.log('User or user.name is not available');
}

// Solution 2: Optional chaining (ES2020)
console.log(user?.name); // undefined (no error)

// Solution 3: Provide default values
const userName = user?.name || 'Guest';
console.log(userName); // Output: Guest

3. SyntaxError: Unexpected token #

Syntax errors occur when JavaScript can't parse your code due to incorrect syntax.

❌ Common Mistakes #

// Missing closing brace
function greet() {
    console.log("Hello");
// SyntaxError: Unexpected end of input

// Missing comma in object
const user = {
    name: "Alice"
    age: 25  // Missing comma
};

// Incorrect arrow function syntax
const add = (a b) => a + b; // Missing comma between parameters

✅ Solutions #

// Correct function syntax
function greet() {
    console.log("Hello");
} // Don't forget the closing brace

// Correct object syntax
const user = {
    name: "Alice",
    age: 25  // Comma added
};

// Correct arrow function
const add = (a, b) => a + b;

4. TypeError: Assignment to constant variable #

This occurs when you try to reassign a const variable.

❌ Common Mistake #

const PI = 3.14;
PI = 3.14159; // TypeError: Assignment to constant variable

✅ Solution #

// Use let if you need to reassign
let approximatePi = 3.14;
approximatePi = 3.14159; // This works

// Or use const for truly constant values
const PI = 3.14159; // Don't reassign this

// For objects and arrays, you can modify contents
const user = { name: "Alice" };
user.name = "Bob"; // This works - modifying property
user.age = 25;     // This works - adding property

const numbers = [1, 2, 3];
numbers.push(4);   // This works - modifying array contents

5. RangeError: Maximum call stack size exceeded #

This is typically caused by infinite recursion.

❌ Common Mistake #

function countdown(n) {
    console.log(n);
    countdown(n - 1); // Never stops!
}

countdown(5); // RangeError: Maximum call stack size exceeded

✅ Solution #

function countdown(n) {
    if (n <= 0) {
        console.log("Done!");
        return; // Base case to stop recursion
    }
    console.log(n);
    countdown(n - 1);
}

countdown(5); // Works correctly

6. TypeError: Array method called on non-array #

This happens when you try to use array methods on non-array values.

❌ Common Mistake #

let data = "hello";
data.forEach(char => console.log(char)); // TypeError: data.forEach is not a function

✅ Solution #

let data = "hello";

// Solution 1: Check if it's an array
if (Array.isArray(data)) {
    data.forEach(item => console.log(item));
} else {
    console.log("Data is not an array");
}

// Solution 2: Convert string to array
const chars = Array.from(data);
chars.forEach(char => console.log(char));

// Solution 3: Use appropriate method for strings
data.split('').forEach(char => console.log(char));

7. Asynchronous Operation Errors #

Common mistakes with promises and async/await.

❌ Common Mistakes #

// Forgetting to handle Promise rejection
fetch('/api/data'); // Unhandled promise rejection

// Using await without async
function getData() {
    const result = await fetch('/api/data'); // SyntaxError
    return result;
}

// Not waiting for async operations
async function processData() {
    const data = fetch('/api/data');
    console.log(data.length); // TypeError: data is a Promise
}

✅ Solutions #

// Handle Promise rejections
fetch('/api/data')
    .then(response => response.json())
    .catch(error => console.error('Error:', error));

// Use async/await correctly
async function getData() {
    try {
        const response = await fetch('/api/data');
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error:', error);
        return null;
    }
}

// Wait for async operations
async function processData() {
    try {
        const response = await fetch('/api/data');
        const data = await response.json();
        console.log(data.length);
    } catch (error) {
        console.error('Error processing data:', error);
    }
}

Debugging Techniques #

1. Console Methods #

// Use different console methods
console.log('Regular log');
console.error('Error message');
console.warn('Warning message');
console.info('Info message');

// Use console.table for objects/arrays
const users = [
    { name: 'Alice', age: 25 },
    { name: 'Bob', age: 30 }
];
console.table(users);

// Use console.group for organized output
console.group('User Details');
console.log('Name: Alice');
console.log('Age: 25');
console.groupEnd();

2. Try-Catch Blocks #

function risky() {
    try {
        // Code that might throw an error
        const result = JSON.parse('invalid json');
        return result;
    } catch (error) {
        console.error('Error caught:', error.message);
        return null;
    } finally {
        console.log('Cleanup code runs regardless');
    }
}

3. Error Objects #

function throwCustomError() {
    throw new Error('Custom error message');
}

try {
    throwCustomError();
} catch (error) {
    console.log('Error name:', error.name);
    console.log('Error message:', error.message);
    console.log('Stack trace:', error.stack);
}

Prevention Tips #

1. Use Strict Mode #

'use strict';

// Prevents common mistakes
function example() {
    undeclaredVar = 5; // ReferenceError in strict mode
}

2. Use TypeScript or JSDoc #

/**
 * Calculates the area of a rectangle
 * @param {number} width - The width of the rectangle
 * @param {number} height - The height of the rectangle
 * @returns {number} The area
 */
function calculateArea(width, height) {
    if (typeof width !== 'number' || typeof height !== 'number') {
        throw new Error('Width and height must be numbers');
    }
    return width * height;
}

3. Validate Input #

function processUser(user) {
    // Validate input
    if (!user || typeof user !== 'object') {
        throw new Error('User must be an object');
    }
    
    if (!user.name || typeof user.name !== 'string') {
        throw new Error('User must have a valid name');
    }
    
    // Process user...
    console.log(`Processing user: ${user.name}`);
}

Common Error Patterns to Avoid #

  1. Not handling async errors
  2. Mutating props in React/Vue
  3. Memory leaks from event listeners
  4. Not validating user input
  5. Ignoring error responses from APIs

Summary #

The most common JavaScript errors are:

  • ReferenceError: Use undefined variables
  • TypeError: Access properties of null/undefined, wrong types
  • SyntaxError: Incorrect code syntax
  • RangeError: Usually from infinite recursion
  • Async errors: Not handling promises properly

Prevention strategies:

  • Use strict mode
  • Validate inputs
  • Handle errors explicitly
  • Use proper debugging techniques
  • Test edge cases

Remember: errors are learning opportunities. Each error teaches you something about how JavaScript works!

Next Steps #

Related Error Solutions

Error SolutionBeginner
4 min min read

Are Java and Bedrock Seeds the Same? Common Confusion

Understand whether Java and Bedrock seeds are the same in Minecraft and how this relates to JavaScript development concepts.

#javascript #java #confusion +2 more
View Solution →

Last updated: Jan 27, 2025

Error SolutionBeginner
4 min min read

Are Java and JavaScript the Same? Common Confusion Explained

Are Java and JavaScript the same? Learn why this common confusion exists and discover the key differences between these two programming languages.

#java #javascript #confusion +2 more
View Solution →

Last updated: Jan 27, 2025

Error Solutionintermediate

Async/Await and Promise Errors - Complete Troubleshooting Guide

Learn to debug and fix common async/await and promise errors in JavaScript. Master error handling patterns for asynchronous code.

#javascript #async #promises +2 more
View Solution →
Error SolutionBeginner
6 min min read

Can JavaScript Be Used for Backend? Common Misconceptions

Address common myths about whether JavaScript can be used for backend development and explore server-side JavaScript capabilities.

#javascript #backend #nodejs +2 more
View Solution →

Last updated: Jan 28, 2025