DEV Community

Discussion on: Uncaught TypeError: Cannot read property 'xyz' of undefined

Collapse
 
linehammer profile image
linehammer

In JavaScript almost everything is an object, null and undefined are exceptions. This error occurs when a property is read or a function is called on an undefined variable. 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.

If you are not sure a variable that will always have some value, the best practice is to check the value of variables for null or undefined before using them. To avoid getting these types of errors, you need to make sure that the variables you are trying to read do have the correct value. This can be done in various ways. You can do if checks before dealing with objects whose values are bound to change:

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

Or

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

net-informations.com/js/iq/unerror...

Collapse
 
jwp profile image
John Peters

Not specifically helpful for the article. The problem was that an incomplete error message forced us to set breakpoints in Angular to find out why.