Error typeerror cannot read properties of undefined reading push

When working with JavaScript arrays, you have to be careful that you are not calling the push(), pop(), shift(), unShift(), or splice() methods on a variable that is meant to be an array but has a value of undefined. If you mistakenly do this, you'll get this error: If you call pop() or any of these other methods instead of push (as in the example above), the error above will carry 'pop' (or the other method you're using) instead. This means the approach you'll learn in the article will work

How to Fix TypeError: Cannot read Property 'push' of Undefined in JavaScript

When working with JavaScript arrays, you have to be careful that you are not calling the push(), pop(), shift(), unShift(), or splice() methods on a variable that is meant to be an array but has a value of undefined.

If you mistakenly do this, you’ll get this error:

s_E70A1833F8285C7F5412DCD9531F13EA1E92CB215392E2D976AD0B6D0DFB9AA0_1665231049694_image

If you call pop() or any of these other methods instead of push (as in the example above), the error above will carry ‘pop’ (or the other method you’re using) instead. This means the approach you’ll learn in the article will work for all methods.

For you to properly understand this article and this error, it is essential to highlight the various reasons that can trigger this issue:

  • You call the method on a variable previously set to undefined.
  • You call the method on a variable before it has been initialized with an array.
  • You call the method on an array element rather than the array itself.
  • You call the method on an object property that does not exist or has an undefined value.

Remember that this method can be push(), pop(), shift(), unShift() or splice(). Let’s now analyze each scenario and learn how to fix the error.

Calling the method on a variable that was previously set to undefined

When working with variables and data types like strings, we tend to assign the variable’s values like undefined and null before passing in the original value. Sometimes we do this when calling functions or handling certain actions.

For arrays, it doesn’t work that way – else, you will get the error:

let myArray = undefined;

myArray.push("John Doe"); // Uncaught TypeError: Cannot read properties of undefined (reading 'push')

console.log(myArray);

To fix this, You must declare that the variable is an array before array methods like the push(), pop(), and others can work on it:

let myArray = [];

myArray.push("John Doe");

console.log(myArray); // ["John Doe"]

Note: When a variable is declared, it is not recognized as an array variable until it is initialized using either the Array constructor or using array literal notation ([]).

Calling the method on a variable before it has been initialized with an array

As you just learned above, another way you can declare variables is to create them without assigning them a value.

let myArray;

myArray.push("John Doe"); // Uncaught TypeError: Cannot read properties of undefined (reading 'push')

console.log(myArray);

This works well for data types like strings, numbers, and others but doesn’t work well for an array. You must initialize arrays with the Array constructor or an array literal notation ([]).

let myArray = [];

// Or

let myArray = new Array();

Our code will now look like this:

let myArray = [];

myArray.push("John Doe");

console.log(myArray); // ["John Doe"]

Calling the method on an array element rather than the array itself

Array methods are meant to be called on the array itself (meaning the array or the variable used to store the array) and not an array element.

// Example of arrays
let myArray = [12, 13, 17];
let myArray2 = [];
let myArray3 = new Array();

// Example of array elements
myArray[0];
myArray[1];
myArray[2];

You might want to push an element to a particular position of an array and think that attaching either the push() or unShift() method to the element directly will fix that. Unfortunately, you will get the «cannot read property ‘push’ of undefined» error:

let myArray = [12, 13, 17];

myArray[3].push(15); // Uncaught TypeError: Cannot read properties of undefined (reading 'push')

console.log(myArray);

To fix this, you have to call the push method on the variable itself and not on its element:

let myArray = [12, 13, 17];

myArray.push(15);

console.log(myArray); // [12,13,17,15]

Calling the method on an object property that does not exist or has an undefined value

A final scenario could be when you try to call the method on an object property that does not exist or whose value is set to undefined:

const user = { name: 'John Doe', scores: undefined };
const user2 = { name: 'John Doe' };

user.scores.push(50);
user2.scores.push(50); 
// Uncaught TypeError: Cannot read properties of undefined (reading 'push')

In the scenario above, there are two objects: the first object has a key-value pair scores whose value is set to undefined, but it’s meant to receive array values. While for the second object, scores does not exist. Both situations can cause errors.

To fix it, all you have to do is initialize the key, so it expects array values using the array literal:

const user = { name: "John Doe", scores: [] };

user.scores.push(50);

console.log(user);

Wrapping Up

In this article, you have learned how to fix the «Cannot read properties of undefined» error, which occurs when you attach these array methods to variables that are not declared or initialized as variables.

Have fun coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

The “cannot read property of undefined” error occurs when you attempt to access a property or method of a variable that is undefined. You can fix it by adding an undefined check on the variable before accessing it.

The "cannot read property of undefined" error in JavaScript.

Depending on your scenario, doing any one of the following might resolve the error:

  1. Add an undefined check on the variable before accessing it.
  2. Access the property/method on a replacement for the undefined variable.
  3. Use a fallback result instead of accessing the property.
  4. Check your code to find out why the variable is undefined.

1. Add undefined check on variable

To fix the “cannot read property of undefined” error, check that the value is not undefined before accessing the property.

For example, in this code:

const auth = undefined;

console.log(auth); // undefined

// ❌ TypeError: Cannot read properties of undefined (reading 'user')
console.log(auth.user.name);

We can fix the error by adding an optional chaining operator (?.) on the variable before accessing a property. If the variable is undefined or null, the operator will return undefined immediately and prevent the property access.

const auth = undefined;

console.log(auth); // undefined

// ✅ No error
console.log(auth?.user?.name); // undefined

The optional chaining operator also works when using bracket notation for property access:

const auth = undefined;

console.log(auth); // undefined

// ✅ No error
console.log(auth?.['user']?.['name']); // undefined

This means that we can use it on arrays:

const arr = undefined;

console.log(arr?.[0]); // undefined

// Array containing an object
console.log(arr?.[2]?.prop); // undefined

Note

Before the optional chaining was available, the only way to avoid this error was to manually check for the truthiness of every containing object of the property in the nested hierarchy, i.e.:

const a = undefined;

// Optional chaining
if (a?.b?.c?.d?.e) {
  console.log(`e: ${e}`);
}

// No optional chaining
if (a && a.b && a.b.c && a.b.c.d && a.b.c.d.e) {
  console.log(`e: ${e}`);
}

2. Use replacement for undefined variable

In the first approach, we don’t access the property or method when the variable turns out to be undefined. In this solution, we provide a fallback value that we’ll access the property or method on.

For example:

const str = undefined;

const result = (str ?? 'old str').replace('old', 'new');

console.log(result); // 'new str'

The null coalescing operator (??) returns the value to its left if it is not null or undefined. If it is, then ?? returns the value to its right.

console.log(5 ?? 10); // 5
console.log(undefined ?? 10); // 10

The logical OR (||) operator can also do this:

console.log(5 || 10); // 5
console.log(undefined || 10); // 10

3. Use fallback value instead of accessing property

Another way to solve the “cannot read property of undefined” error is to avoid the property access altogether when the variable is undefined and use a default fallback value instead.

We can do this by combining the optional chaining operator (?.) and the nullish coalescing operator (??).

For example:

const arr = undefined;

// Using "0" as a fallback value
const arrLength = arr?.length ?? 0;

console.log(arrLength); // 0


const str = undefined;

// Using "0" as a fallback value
const strLength = str?.length ?? 0;

console.log(strLength); // 0

4. Find out why the variable is undefined

The solutions above are handy when we don’t know beforehand if the variable will be undefined or not. But there are situations where the “cannot read property of undefined” error is caused by a coding error that led to the variable being undefined.

It could be that you forgot to initialize the variable:

let doubles;

let nums = [1, 2, 3, 4, 5];

for (const num of nums) {
  let double = num * 2;

  // ❌ TypeError: cannot read properties of undefined (reading 'push')
  doubles.push(double);
}

console.log(doubles);

In this example, we call the push() method on the doubles variable without first initializing it.

let doubles;

console.log(doubles); // undefined

Because an uninitialized variable has a default value of undefined in JavaScript, accessing a property/method causes the error to be thrown.

The obvious fix for the error, in this case, is to assign the variable to a defined value.

// ✅ "doubles" initialized before use
let doubles = [];

let nums = [1, 2, 3, 4, 5];

for (const num of nums) {
  let double = num * 2;

  //  push() called - no error thrown
  doubles.push(double);
}

console.log(doubles); // [ 2, 4, 6, 8, 10 ]

Another common mistake that causes this error is accessing an element from an array variable before accessing an Array property/method, instead of accessing the property/method on the actual array variable.

const array = [];

// ❌ TypeError: Cannot read properties of undefined (reading 'push')
array[0].push('html');
array[0].push('css');
array[0].push('javascript');

console.log(array);

Accessing the 0 property with bracket indexing gives us the element at index 0 of the array. The array has no element, so arr[0] evaluates to undefined and calling push() on it causes the error.

To fix this, we need to call the method on the array variable, not one of its elements.

const array = [];

// ✅ Call push() on "array" variable, not "array[0]"
array.push('html');
array.push('css');
array.push('javascript');

console.log(array); // [ 'html', 'css', 'javascript' ]

Conclusion

In this article, we saw some helpful ways of resolving the “cannot read property of undefined” error in JavaScript. They might not resolve the error totally in your case, but they should assist you during your debugging.

Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.

Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

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");
}

The TypeError: Cannot read property of undefined is one of the most common type errors in JavaScript. It occurs when a property is read or a function is called on an undefined variable.

Install the JavaScript SDK to identify and fix these undefined errors

Error message:

TypeError: Cannot read properties of undefined (reading x)

Error type:

TypeError

What Causes TypeError: Cannot Read Property of Undefined

Undefined means that a variable has been declared but has not been assigned a value.

In JavaScript, properties and functions can only belong to objects. Since undefined is not an object type, calling a function or a property on such a variable causes the TypeError: Cannot read property of undefined.

TypeError: Cannot Read Property of Undefined Example

Here’s an example of a JavaScript TypeError: Cannot read property of undefined thrown when a property is attempted to be read on an undefined variable:

function myFunc(a) {
console.log(a.b);
}

var myVar;
myFunc(myVar);

Since the variable myVar is declared but not initialized, it is undefined. When it is passed to the myFunc function, the property b is attempted to be accessed. Since a is undefined at that point, running the code causes the following error:

TypeError: Cannot read properties of undefined (reading 'b')

How to Avoid TypeError: Cannot Read Property of Undefined

When such an error is encountered, it should be ensured that the variable causing the error is assigned a value:

function myFunc(a) {
    console.log(a.b);
}

var myVar = {
    b: 'myProperty'
};

myFunc(myVar);

In the above example, the myVar variable is initialized as an object with a property b that is a string. The above code runs successfully and produces the following output on the browser console:

myProperty

To avoid coming across situations where undefined variables may be accessed accidentally, an if check should be added before dealing with such variables:

if (myVar !== undefined) {
    ...
}

if (typeof(myVar) !== 'undefined') {
    ...
}

Updating the previous example to include an if check:

function myFunc(a) {
    if (a !== undefined) {
        console.log(a.b);
    }
}

var myVar;
myFunc(myVar);

Running the above code avoids the error since the property b is only accessed if a is not undefined.

Here is how you can handle errors using a try { } catch (e) { } block.

// Caught errors
try {

  //Place your code inside this try, catch block
  //Any error can now be caught and managed

} catch (e) {
  Rollbar.error("Something went wrong", e);
  console.log("Something went wrong", e);
}

Here is how you can setup a JavaScript Error handler: Setup JavaScript Error Handler

Where TypeError Resides in the JavaScript Exception Hierarchy

JavaScript provides a number of core objects that allow for simple exception and error management. Error handling is typically done through the generic Error object or from a number of built-in core error objects, shown below:

  • Error
  • InternalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
    • Cannot read property of undefined

As seen from the hierarchy above, TypeError is a built-in JavaScript error object that allows for the administration of such errors. The “Cannot read property of undefined” TypeError is a descendant of the TypeError object.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing JavaScript errors easier than ever. Sign Up Today!

Понравилась статья? Поделить с друзьями:
  • Error typeerror cannot read properties of undefined reading length
  • Error typed files cannot contain reference counted types
  • Error typecheck offendingcommand show
  • Error typecheck offendingcommand makefont
  • Error typecheck offending command setdash