Author -  Sai gowtham

Resolve the JavaScript error "Cannot read Property 'push' of Undefined"

The “cannot read property ‘push’ of undefined” issue in JavaScript happens when you attempt to invoke the push() method on a variable that should contain an array but instead contains the value undefined or null.

The “Cannot read properties of undefined (reading ‘push’)” error can happen for a number of reasons:

  1. Using the push() method on a variable that holds a value of “undefined” or “null”.

  2. Calling the push() method in an array at a certain index.

  3. Forgot to initialize a array and trying to use pus() method on it.

  4. Calling a push() method on a object or string.

Here is an example, how the error occurs:

const arr = null;
arr.push(3);

Output:

VM568:2 Uncaught TypeError: Cannot read properties of null (reading 'push')
    at <anonymous>:2:5

To fix this error, make sure to initialize a proper array [] to the variable before calling a push() method on it.

Here is an example:

const arr = [];
arr.push(3);

console.log(arr); // [3]

We can also check, if the given value is an type array or not before calling the push() method on it. So that, we can avoid this type of runtime errors.

Here is an example, how to check given variable is array or not:

var arr = [1, 2, 3];

if(Array.isArray(arr)){
    arr.push(4);
}else{
    console.log("Given data is not an array")
}

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY