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:
-
Using the push() method on a variable that holds a value of “undefined” or “null”.
-
Calling the push() method in an array at a certain index.
-
Forgot to initialize a array and trying to use pus() method on it.
-
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")
}