DEV Community

loading...

JS Bites: Could not read something of undefined

ranewallin profile image Rane Wallin ・2 min read

Error that reads "Cannot read property 'color' of undefined"

I tutor and mentor new developers in Javascript. By and large, the most common error they come across is "Cannot read some_property of undefined." An experienced developer will usually understand instantly what's gone wrong, but for new developers it can lead to sometimes hours of frustration.

So, what does it really mean?

In the most simple terms, this error means that a thing you are trying to access the properties on either does not exist or is not what you think it is.

Here are a couple of examples

const result = await axios.post(API_URL, user);

console.log(result.data.user.name + " has been added to the database!");

In the above example, the front end team thought the back end would return a copy of the new user data in its response. In reality, the back end was just returning "Success." This results in the console.log() returning an error that it Cannot read name of undefined.

let cats = [
    {
        name: "Grumpy",
        color: "Grey"
    },
    {
        name: "Heathcliff",
        color: "Orange",
    },
    {
        name: "Felix",
        color: "Black"
    }
  ];

console.log(cats.grumpy.color);

In the above example, a new developer did not properly understand how to work with objects, particularly arrays of objects.

What to do when you see this error?

Any time you are working with data, you should console.log() the data before you start working with it, even when you are sure you know what it is. Once you see the data, it's often immediately clear what is going wrong.

If I am passing data from one place to another (back end to front end, through React props, from one function to another, etc), I like to log out the data before it's passed and after. This allows me to confirm that things are passing through the way that I expect them to.

You can also use an extension like Quokka, which allows you to see live code coverage and your console.log()s right in your editor.

The most important thing, though, is just keep coding. The more errors you see, the more errors you will eventually know how to fix. People who have the answers have them because they once had the questions.


 JS Bites

 Have you ever need a quick solution to a problem, but when you search 
 Google you are met with pages of tutorials and detailed instructions that 
 bury the information you need? That's what JS Bites attempts to solve. 
 Each post is a small, bite-sized primer on a very specific JS topic. The 
 aim is to provide enough detail to boost understanding, but not so much that 
 you become overwhelmed or lost.

Discussion (0)

pic
Editor guide