Javascript cannot read property of undefined – How to Fix Cannot read Property of Undefined Error in JavaScript

Javascript cannot read property of undefined: There are three main causes of the “Cannot read property of undefined” error:

  • When we access a property on a variable that holds an undefined value.
  • When we access a non-existent property on a DOM element.
  • When we Insert the JavaScript <script/> tag above the HTML, where the DOM elements are declared.

The error most typically happens when you attempt to access a property on a variable that has an undefined value.

index.js:

const employ = undefined;

// Here the variable `employ` is undefined so when we try to
// access the `salary` property on the above variable that holds an
// undefined value we get an ERROR
employ.salary;

Output:

employ.salary;
^

TypeError: Cannot read property 'salary' of undefined
at Object.<anonymous> (/tmp/MOncfvGk3U.js:6:8)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here the variable `employ` is undefined so when we try to access the `salary` property 
on a variable that holds an undefined value we get an ERROR

Fixing Cannot read Property of Undefined Error in JavaScript

Method #1: Using Optional Chaining(.)

Cannot read property of undefined javascript: To fix the “Cannot read property of undefined” error, use the optional chaining (.) operator to ensure that the variable, for example employ.salary, is not null before accessing it.

Instead of throwing an error, the operator short-circuits if the variable is undefined or null.

// Take a variable and initialize its value with undefined
const employ = undefined;

// Print the salary property/attribute of the employ if it is doesn't exists then it prints undefined
console.log(employ.salary); 
console.log(employ.salary.month); 

Output:

Undefined
Undefined

Explanation:

Javascript cannot read property of undefined: The optional chaining (.) operator enables us to access an object’s property without throwing an exception if the reference is invalid.

If the reference is equal to undefined or null, the optional chaining (.) operator returns undefined instead of raising an error.

Method #2: Using if-Else Conditional Statements

// Take a variable and initialize its value with undefined
const employ = undefined;

// Check if the salary attribute is present in employ using optional chaining(.) and if conditional statement
if (employ.salary) {
// If is is true(exists) print that corresponding value 
  console.log(employ.salary);
} else {
    // Else print some random text for acknowledment
  console.log('The employ.salary is NOT found');
}

Output:

The employ.salary is NOT found

Method #3: Using logical AND (&&) operator

// Take a variable and initialize its value with undefined
const employ = undefined;

// Here we use logical AND(&&) operator to check whether the property/attribute exists or not
console.log(employ && employ.salary); 

Output:

undefined

Explanation:

Here we used the logical AND (&&) operator, which ignores the value to the right 
if the value to the left is false (example- undefined).

When trying to access an array element at an index that does not exist in the array, you frequently obtain undefined results.

// Give an empty array and store it in a variable
const gvn_arry = [];

// This is a BAD approach
// Here we get i.e, Cannot read property 'website' of undefined
console.log(gvn_arry[0].website); 

// This is a GOOD approach
console.log(gvn_arry[0].website); 

// This is a GOOD approach
console.log(gvn_arry[0] && gvn_arry[0].website); 

Output:

Undefined

Undefined

Before attempting to access a variable, ensure that it has been declared in your code; otherwise, you will receive the “X is not defined” error.

Accessing a non-existent property on a DOM element.

Another common cause of the error is attempting to access a property on a DOM element that does not exist.

To resolve the “Cannot read property of undefined” problem, verify that the DOM element you are attempting to access exists. When attempting to access the property at a non-existent index after using the getElementsByClassName() method, the error is frequently thrown.

index.js:

// Get the element by class name which doesn't exist

const htmlboxes = document.getElementsByClassName('doesNotExist');
console.log(htmlboxes );

// Here we get an error => Cannot read properties of undefined (reading 'innerHTML')
console.log(htmlboxes [0].innerHTML);

Output:

Cannot read properties of undefined (reading 'innerHTML')

Instead, correct the class name and use the optional chaining (.) operator to see if the property is present in the element at the index 0.

Using Optional Chaining and If else Conditional statements:

// Get the element by class name which doesn't exist 
const htmlboxes = document.getElementsByClassName('doesNotExist');
console.log(htmlboxes ); 

// Check if the element exists using the optional chaining(.)
if (htmlboxes[0].innerHTML) {
  console.log(htmlboxes [0].innerHTML);
} else {
  // If the element doesnt exist then print some random acknowledgement
  console.log('The element is not FOUND');
}

If the element at index 0 has the innerHTML property, the if block is executed; otherwise, the else block is executed.

To resolve the “Cannot read property of undefined” error, place the JS <script/> tag at the bottom of the body. After the HTML elements have been declared, the JS script tag should be inserted.

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <script src="index.js"></script>

    <!-- The HTML elements must be above the JS script tag,
    otherwise they cannot be accessed
    This is a BAD approach-->
    
    <div class="box">Btechgeeks</div>
  </body>
</html>

The index.js script tag is executed before the declaration of the div element with the class name box.

The div element will not be available if you try to access it in the index.js script, resulting in the error.

index.js:

// Get the element by class name which doesn't exist 
const htmlboxes = document.getElementsByClassName('doesNotExist');
console.log(htmlboxes); // []

// Here we get Cannot read properties of undefined (reading 'innerHTML') Error
console.log(htmlboxes[0].innerHTML);

So, the JS script must be placed at the bottom of the body, after the HTML elements have been declared.

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <!--Here the HTML elemets are declared first -->
    <div class="box">Btechgeeks</div>

    <!-- Here the Js script tag is palced at the bottom of the body after the declaration of HTML elements
    which is a GOOD Approach>
    <script src="index.js"></script>
  </body>
</html>
Inside the index.js script, the div element with the class name box is now accessible.

index.js:

// Get the element by class name which doesn't exist 
const htmlboxes = document.getElementsByClassName('doesNotExist');
console.log(htmlboxes); // []

// Here we get Cannot read properties of undefined (reading 'innerHTML') Error
console.log(htmlboxes[0].innerHTML);

In Brief

When attempting to access a property on an undefined value, the “Cannot read property of undefined” error occurs.

Undefined values are frequently returned when:

  • when we access a property on an object that does not exist.
  • when we access an index in an array that does not exist