How to Fix: cannot read property of undefined JavaScript

The error “Uncaught TypeError: Cannot read properties of undefined” occurs when we are trying to access a property from a null or undefined object. A more direct approach is assigning the variable with more appropriate values to avoid “undefined” values.

undefined JavaScript error
JavaScript error

The four common ways to fix the “cannot read property of undefined JavaScript” error are as follows:

  1. Wrap the code in a try…catch() to avoid the error from breaking the application. Additionally, console.log statements in the catch() section will provide more help with debugging.
  2. If the error is caused by a variable associated with an async operation, JavaScript concepts such as async/await, Promise, etc, must be used to ensure that the object property is accessed after the time delay.
  3. When the error is associated with a DOM element, the “defer” attribute in HTML <script> tag ensures the execution of JavaScript code after the browser window is completely loaded.
  4. The Optional chaining(?.) JavaScript feature only accesses defined properties from the object or returns undefined, thus avoiding errors.

1) Debug error with try…catch() statement

Wrapping the JavaScript code with a try statement prevents JavaScript errors from breaking the application. The try…catch() statement is executed as follows:

  1. Execute JavaScript code of the try {} section until any error is encountered.
  2. If a JavaScript error occurs, the execution of the remaining code of try {} section is skipped, and catch {} section is executed.
  3. Only try {} section is executed when no error is encountered.
try {
  var employee;
  console.log(employee.name)
} catch (error) {
  // employee value
  console.log(employee)
  // error details
  console.error(error);
}

2) Accessing properties from variables associated with Async operation

Sometimes, JavaScript code is very tricky with a combination of synchronous and asynchronous operations. The variable’s value can be “undefined” if it is dependent on an async function.

The undefined error caused by asynchronous execution must be fixed through JavaScript concepts such as Promise, Async/Await, etc.

var employee; //undefined

// 2 seconds time delay
setTimeout(() => {
  employee = { name: "Emp1" };
}, 2000);

console.log(employee.name) //Error

/* Solution */

// Timeout function wrapped by JS Promise
function getEmployeeDetails() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({ name: "Emp1" });
    }, 2000);
  });
}

// Handle time delay with Async/Await
var employee = await getEmployeeDetails();
console.log(employee.name) //Emp1

3) Accessing DOM element before window load

When HTML DOM elements are accessed in JavaScript, it is important to ensure that JavaScript code is executed after the browser window is loaded. Any attempts to access DOM elements before loading HTML code will lead to undefined or null errors.

<html>
<head>
<title>Page Title</title>
<script>
  var container = document.getElementById("main");
  container.innerText = "Sample Text"; //Error
</script>
</head>
<body>

<div class="id"></div>

</body>
</html>

The “defer” attribute of the <script> tag ensures that the JavaScript code is executed after the browser window is completely loaded.

<!-- Solution -->
<script defer>
  var container = document.getElementById("main");
  container.innerText = "Sample Text";
</script>

4) Optional chaining (?.)

In some scenarios, function or REST API calls are expected to return a “null” value. Accessing properties from “undefined” or “null” objects will throw a JavaScript error.

The optional chaining (?.) feature in JavaScript allows accessing object properties that may or may not exist without causing any error. This feature is especially useful when dealing with nested objects.

var employee;
console.log(employee.name) //Error

console.log(employee?.name) //undefined
console.log(employee?.address?.city) //undefined

5) Handling Array objects

Accessing JavaScript array-based properties from an “undefined” variable is another cause for the error. Therefore, every Array-based object must be assigned with “[ ]”(empty array) as the default value.

var employeeList;

//Error
if(employeeList.length == 0){
  console.log("no Emplyees");
}

/* Solution */
employeeList = [];
if(employeeList.length == 0){
  console.log("no Emplyees");
}