Javascript cannot read property of undefined – What Now?

Hello everyone, if you ever used Javascript im sure you came across the following errors: javascript cannot read property of undefined OR javascript cannot read property of null.

Now, if you’re a strong javascript developer these kinds of errors are in your past. Moreover, you seldom encounter them. However, many javascript developers, and especially beginner ones face these kinds of errors on a regular basis.

Today Im going to explain why we encounter such errors. In addition, I will give you a few development guidelines that will help you solve such problems and even avoid them in the future. So without any further delay lets begin!

Javascript cannot read property of null: What Is this?

Before we dive in and talk about why and how to solve/avoid such errors, let me first explain them.

Javascript cannot read property of undefined or javascript cannot read property of null are two errors which point to the same problem, sort of speak. You are trying to perform some sort of action on a variable which hasn’t been defined, or, simply doesn’t hold any value, thus returning null or undefined depending on the case. In order to better understand the nature of the problem, let’s take a look at the following code example:

<script>
    // GET ME SOMETHING
    let ele = document.getElementById('someID');

    // PERFORM AN ACTION ON IT
    ele.setAttribute('aria-label','Hello');
</script>

Now, this looks pretty straightforward right? I featching an element from the DOM and I want to manipulate it, in other words, I want to perform some kind of action on it. Well, if I will go to my console now, I will have an error:

javascript cannot read property of null

Moreover, I can tell you that if you have more code written below that “action” it won’t run. This is related to the way Javascript works(that’s a subject for another day). So basically now your whole code below that error doesn’t work.

Simply put, you’re trying to perform an action on an empty variable, resulting in an error thrown by javascript.

Javascript cannot read property of undefined

As mentioned above, the concept idea is very similar. However, it does hold a small difference. You will most likely encounter this error if a variable’s value hasn’t been set yet. Meaning, if you will try to perform a sort of action or dom-manipulation with that variable and it hasn’t been initialized yet, Let’s take a look at the example below:

<script>
    // SET VARIABLE WITHOUT ANY VALUE
    let testDef;
    // LETS SEE WHAT IT HOLDS (undefined will be printed here, it holds no value)?
    console.log(testDef);
    // LETS RUN AN ACTION ON IT ( undefined error will be prined here )
    testDef.setAttribute('test','test');
</script>

Now, the result live:

Javascript cannot read property of undefined

In simple terms, a variable without a value will throw an undefined error.

The Solution

Coming up to the more practical part, how do we fix it? First of all, now that we understand why it happens, we can avoid it right off the bat. Thus, preventing these kinds of errors even originating in later and more complex stages of the project.

Now keep in mind, if such problems arise in advanced development stages, they can be quite of a headache. However, sometimes they can occur even with our guidelines and neat code. For instance: if you fetch something from an API to a variable and it returns an empty value somewhere/somehow. This will definitely result in these errors, but in this case, it’s not by your hand.

So How do we avoid such errors? The answer is simple! We simply enclose our variable before performing any action on it. Now keep in mind, theres even wider scope to be used here. It’s all depending on the environment you’re working on. However, I find it best practiced when this is performed on each variable you know that might be empty or undefined.

For instance: If you’re working on a WordPress template, you want to perform some dom-manipulation on elements located only on the “About Us” page. These elements are unique only to that page. Meaning, if we write our script in the main js file it will be included by WordPress to all pages by default. Thus creating undefined and null errors on other pages where these elements simply do not exist.

We “SCOPE” it. in this case I can even scope it to the about us page id, however, I will do it on every variable as mentioned for stricter use. two examples below:

Scoped by a variable:

<script>
    // SET VARIABLE WITHOUT ANY VALUE
    let testDef;
    // CHECK IF IT HOLDS VALUE
    if (testDef != null){
        testDef.setAttribute('test','test');
        console.log(testDef);
    }
</script>

Multiple element manipulation scoped to a specific page(WP):

<script>
    // GET WORDPRESS PAGE/POST CLASS
    let pageBodyClass = document.getElementsByTagName('body');
    if (pageBodyClass.classList.contains('postid-1')){
        
        // IF YOU ARE SURE THAT THESE ELEMENTS EXSIST ON THIS PAGE, NO NEED
        // TO WRAP SINGLE VARIABLES TOO
        let testDef = document.getElementById('someElemnet');
        testDef.setAttribute('test','test');
        console.log(testDef);
    }

</script>

A little twist!

What if you have some sort of variable only defined after a certain chain of events/timeouts? Meaning, what if you perform some sort of action before you know it has been surely defined. In that case, we do wrap every variable for a 100% error-proof code. Moreover, we enclose our code that we know is depended on some other timeouts or events in its own timeout function.

To sum up

Well, I really hope things are clear about these kinds of errors. It’s really straightforward. Feel free to comment below if something is not clear. In addition, you can read more Javascript related articles here or visit the official Javascript MDN here.

Leave a Reply

Your email address will not be published. Required fields are marked *