I try to access an array events : [data,data,data,length]
with the following code I tried the following 3 things but kept getting these errors respectively for the code below:
console.log(events.length)
let def = 0;
let i = 0;
while(def !== undefined){
def = events[i];
console.log(events[i]);
i++
}
for(i = 0; i < events.length; i++){
console.log(events[i]);
}
Cannot read properties of undefined (reading 'length')
,
Cannot read properties of undefined (reading '0')
,
Cannot read properties of undefined (reading 'length')
Getting the same error when using array.forEach
or array.map
2
Answers
That’s a null reference error. Your event is not defined so accessing its length property by
events.length
will throw an error.The errors you’re seeing (Cannot read properties of undefined) suggest that the events array itself might be undefined at the time you’re trying to access it
If you want to loop through events, you can check its existence first to avoid runtime errors:
If events is being assigned dynamically (e.g., from an API call), make sure it’s initialized to an empty array ([]) or handled asynchronously so that it doesn’t stay undefined when accessed.