Skip to content Skip to sidebar Skip to footer

Why I Am Getting, Cannot Read Property Of Undefined Error?

This code gives me error but this code not why? I am using chrome Version 53.0.2785.116 (64-bit) - Macbook air 2014

Solution 1:

As per snapshot, you are using chrome and Chrome supports .forEach from a long time. My guess is, issue is due to minification or missing semicolon(;)

Sample

functiontest(){
  this.name = "test";
}

var a = newtest()['width', 'height'].forEach(key => {
  console.log(key);
});

Solution 2:

You've omitted whatever is actually causing the problem from your code.

Immediately before the [ you must have something which refers to an object.

This means that the [] syntax becomes the syntax to read a property value instead of the syntax to create an array.

Then (because you are using a comma operator) 'width', 'height' resolves as 'height' so you are trying to read the height property.

Since there is no height property on whatever the object is, you get undefined which doesn't have a forEach property.

To fix this put a semicolon at the end of the previous statement.

The second version of your code works because the var statement can't follow the syntax you have just before it, so it triggers automatic semicolon insertion.

Post a Comment for "Why I Am Getting, Cannot Read Property Of Undefined Error?"