• Register
100 points
7 4

When javascript engine is unable to read property ‘include’ it shows the error cannot read property ‘includes’ of undefined. This article will discuss the error with explanation, cause and the solution.

Explanation

The error is trying to say that we are accessing a property on an undefined object. It does not have that property at all, hence it is undefined. 
But the real problem shows when we have that property in our code but still it shows that error. For example,
var exists = msgArr.objectId.includes(data.objectId);

if(exists === false){
   msgArr.push({"objectId":data.objectId,"latLont":data.latLont,"isOnline":data.isOnline});
}

The Array

var msgArr = [
  {isOnline:true,latLont:"123",objectId:"on0V04v0Y9"},
  {isOnline:true,latLont:"1",objectId:"FpWBmpo0RY"},
  {isOnline:true,latLont:"48343",objectId:"Qt6CRXQuqE"} 
 ]

 

 here the programmer wants to check if a data.objectId already exists in the array. The array contains that specific objectId and it can, but the javascript engine shows error.
 

Cause

Since the javascript array object has no property objectId but looking at the code, it is clear that they have it. 
 

Solution

To check if the objectId or to check if a certain element exists we can use the Array Prototype Some method. So we have to change the method to check if the objectId exists. We need to change our code to check the Id to this.

var exists = msgArr.some(o => o.objectId === data.objectId);

Hope this will help.
 

100 points
7 4