Back to Tutorials
JavaScript
12 min read
Sahasransu Satpathy
9/1/2025

JavaScript TypeError & ReferenceError Fix

Learn why TypeError and ReferenceError occur in JavaScript and how to debug and fix them effectively.

<h2>Introduction</h2>
<p>While working with JavaScript, two of the most common errors developers face are <strong>TypeError</strong> and <strong>ReferenceError</strong>. These errors can be confusing at first, but once you understand the cause, they are easy to fix.</p>

<h3>1. What is a TypeError?</h3>
<p>A <strong>TypeError</strong> happens when you try to perform an invalid operation on a value of the wrong type.</p>

<h4>Examples</h4>
<pre><code>// Example 1: Calling a non-function

const num = 42; num(); // ❌ TypeError: num is not a function

// Example 2: Accessing property of undefined let user; console.log(user.name); // ❌ TypeError: Cannot read properties of undefined </code></pre>

<h4>Fix</h4>
<pre><code>// Fix 1

function greet() { console.log("Hello!"); } greet(); // ✅ works

// Fix 2 let user = { name: "John" }; console.log(user.name); // ✅ John </code></pre>

<h3>2. What is a ReferenceError?</h3>
<p>A <strong>ReferenceError</strong> happens when you try to access a variable that has not been declared.</p>

<h4>Examples</h4>
<pre><code>// Example 1: Undeclared variable

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

// Example 2: Wrong variable name let count = 10; console.log(cnt); // ❌ ReferenceError: cnt is not defined </code></pre>

<h4>Fix</h4>
<pre><code>// Fix 1: Declare variable first

let myVar = 5; console.log(myVar); // ✅ 5

// Fix 2: Use correct variable name let count = 10; console.log(count); // ✅ 10 </code></pre>

<h3>3. Common Debugging Tips</h3>
<ul>
  <li>Check your spelling (typos cause ReferenceErrors).</li>
  <li>Use <code>console.log()</code> to debug variable values.</li>
  <li>Check if a variable is <code>undefined</code> before accessing properties.</li>
  <li>Initialize variables before using them.</li>
</ul>

<h3>4. Using Optional Chaining (Modern Fix)</h3>
<pre><code>// Avoid TypeError when accessing nested properties

let user = {}; console.log(user?.profile?.name); // ✅ undefined (no error) </code></pre>

<h3>Conclusion</h3>
<p>Both <strong>TypeError</strong> and <strong>ReferenceError</strong> are common in JavaScript, but with clear debugging steps, they’re easy to fix. Always initialize variables, double-check names, and use optional chaining to avoid runtime crashes.</p>

Previous Tutorial

Browse All Tutorials