Cannot Read property of Undefined/null in JavaScript
The title is a familiar javascript error we all have encountered. Not just in the js, we get a similar error message when we try to call function on an undefined variable.
Example
In the example x is null and y is undefined.
When we make a call to any js function in null or undefined we get such error messages.
Yes, we don't directly make function calls to a null or undefined value but the objects or variables we use or derive from other variables or the variable used in the loop whose value will be different in each iteration might be null or undefined. Now when we apply js functions like toString(), trim() or properties such as length. We get such errors.
The takeaway from here is that whenever you are using such a method or property make sure that the value you are applying to is not null or undefined. Before applying them always double check if your code will ever have a case where the value might be null or undefined.
Let's take one more example.
In the last line, x["3"].length, we are first extracting the value from x object based on the key "3". But no such key exists, which means the result will be undefined. Now applying length property on undefined will result in error.
How to solve such case?
Here we can check first if the x["3"] is null/undefined.
let z = x["1"] ? x["1"].length : 0
Or we can check of this key exist in the object
let z = x.hasOwnProperty('1')? x["1"].length : 0