Error Explained: Cannot read properties of undefined/null (reading '[property name]')

tl;dr

The object that comes before the property in parentheses does not have a value (meaning: it is undefined or null). Check where it was supposed to be assigned a value to determine why not.

General

šŸ’” Note: this error is shown for either undefined or null, so I will refer to the former, which is more common.

Of all the errors encountered when starting to learn JavaScript, this may be the most frequent and most confusing.

It happens so much because the value undefined(MDN article) appears for many reasons.

For example, this error will happen in each of these (try them in the console!):

  • When a parameter passed to querySelector() is wrong, it cannot find a matching element and will return undefined:

      document.querySelector("NotAnElement").innerText
    
  • An elementā€™s attribute being misspelled or not correctly capitalized yields undefined:

      document.querySelector("div").parenttttNode.parentNode
    
  • Using an index outside of an array is also undefined:

      const studentArray = ['Alice', 'Bob']
      studentArray[studentArray.length + 1].name
    
  • A function with no return statement also returns undefined:

        function multiply(a, b) { 
          let c = a * b   // answer is calculated, but no return statement
        } 
        let twoDozen = multiply(2, 12)
        console.log(twoDozen.toFixed(2))  // <=== Error happens here
    
  • A variable that is declared but not assigned a value defaults to undefined:

        let studentA = { name: "Joseph", age: 24, field: "Computer Science" }
        let studentB  // this "declares" (creates) a variable but gives it no value
        console.log(studentA.field)  // outputs "Computer Science"
        console.log(studentB)        // outputs undefined
        console.log(studentB.field)  // <=== Error happens here
    

In this last block of code, the studentB variable was *declared (*and initialized), but it was never assigned a value, so its value is undefined. That is why we can console.log(studentB), but can not console.log(studentB.field)

For more on the terms declaration and assignment, hereā€™s a simple explanation as well as a bit more on JavaScriptā€™s declaration mechanics:

https://www.sitepoint.com/how-to-declare-variables-javascript/

Because the error is so common and often misleading by pointing at the property, I try to explain what this means to students so that they can better remember how to quickly address the bug.

Understanding the Error Message

To walk through parsing the error message, let's reuse this code from above:

let studentB  // this "declares" (creates) a variable but gives it no value
console.log(studentB.field)  // <=== Error happens here

The key to understanding this error is the word ā€œreadā€ which appears twice:

Cannotreadproperties of undefined (readingā€˜fieldā€™)

Those refer to the same operation which caused this error. Knowing this, we can simplify the message by removing the redundancy and substituting the general "properties" for the specific property in question, "field":

Cannot read property ā€˜fieldā€™ of undefined

Which is a lot closer to English, but perhaps not quite clear yet.

The second hint is ā€œofā€, a word with ten different dictionary definitions. In software development, "of" is seen a lot when learning Object Oriented Programming and means this third one from the Oxford English Dictionary:

3. Indicating an association between two entities, typically one of belonging ("the son of a friend").

Substituting gives us:

Cannot read property ā€˜fieldā€™ which belongs to undefined

The last bit is missing: an implied "value", which may refer to a variable such as studentB. Adding that on:

Cannot read property 'field' which belongs to an undefined value

At this point, weā€™ve reached an English-like sentence that makes it fairly clear that the problem isnā€™t the mentioned property, but the undefined value to which it was supposed to belong.

The error mentions field to help point us to the actual place of the error. We could fully clarify this by rewriting:

Cannot read property 'field' *because* it belongs to an undefined value

Now it makes sense and tells us where to start looking for the problem!

An alternative rewriting

Fellow grammar nerds may have noticed something interesting about the language of the error.

The part in parentheses is JavaScript saying something specific about our code: ā€œyou asked me to use the property ā€˜fieldā€™).

Whereas the first part describes a more general statement: ā€œyou canā€™t use properties of an undefined valueā€.

Combining these can also help point out the cause of the error:

You asked me to use the property ā€˜fieldā€™, but you canā€™t use properties of an undefined value!

Conclusion

I've been mentoring bootcamp students at Resilient Coders for several years and this error always pops up, starting with the first or second week of Javascript. Unfortunately, I've seen it continue to trip up these new coders throughout the entire months-long program, causing a terrible amount of frustration and wasted time.

Noticing the trend I reflected on why these seven words are so difficult, even recalling the first or several times it confused me. And why wouldn't it- look at how much parsing I had to do to translate it into English! While working with students in the last few cohorts I slowly developed this way of explaining not only what the problem is, but how to read the error.

So why not give us the name of the variable which is undefined in the first place? Possibly as I mentioned earlier- it may not be a variable- see the partial list of reasons undefined pop up earlier. Nobody even knows how long it might be. After working with Javascript for a while, you'll understand that it could be a long function with no name and a thousand lines of code- that certainly wouldn't be helpful! What should be put in the error message then? Turns out that's not an easy question.

For example, if our code was ā€¦parentNode.parentNode.attribute and one of those parents is undefined- an error message saying ā€˜parentNode is undefinedā€™' does not help as much as ā€˜the thing before attribute/parentNode is undefinedā€™. I think this compromise gives us a useful error but unfortunately, the way it was written is extremely unfriendly to those learning to code. Maybe because nobody used Javascript when learning how to code twenty years ago.

Let me know if you found this helpful and if there are other error messages you'd like to understand.

Ā