Uncaught TypeError: Cannot read property ‘x’ of undefined
The issue:
In our case we had a large JavaScript file where we had a JavaScript variable declared. The variable didn’t have any value assigned to it. At some point we were assigning a property with a value like below:
var userInfo; userInfo.name = 'Joe Smith';
As soon as we tried that we got into the following issue:
Uncaught TypeError: Cannot set property 'name' of undefined
The reason of the issue
The variable is declared but the type is not defined. So the variable is undefiend. Now when we tried to set a property called name
on an undefined variable it throws the Uncaught TypeError.
The solution
To solve this issue we need to define the variable. In this case if we define the variable to object type then the issue will resolved. See the code below:
var userInfo = {}; userInfo.name = 'Joe Smith';
As we have declared the variable as object, we can set any property on that variable.