Objects don't have a .length property.

A simple solution if you know you don't have to worry about hasOwnProperty checks, would be to do this:

Object.keys(data).length;

If you have to support IE 8 or lower, you'll have to use a loop, instead:

var length= 0;
for(var key in data) {
    if(data.hasOwnProperty(key)){
        length++;
    }
}
Answer from Cerbrus on Stack Overflow
Discussions

javascript - Array length and undefined indexes - Stack Overflow
In your case, since only 2 is a valid property in the array, it will be counted. But, when you print arr[4], it prints undefined, because JavaScript will return undefined, if you try to access a property which is not defined in an object. For example, ... Similarly, since 4 is not yet defined in the arr, undefined is returned. While we are on this subject, you might want to read these answers as well, Why doesn't the length ... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Why array[array.length] returns undefined? - Stack Overflow
JavaScript array indexes start counting at 0. So... ... Save this answer. ... Show activity on this post. Arrays are 0-indexed. The last item of the array can be accessed with arr[arr.length - 1]. In your example, you're attempting to access an element at an index that doesn't exist. More on stackoverflow.com
🌐 stackoverflow.com
javascript - Array length undefined - Stack Overflow
I'm trying to get the length of a multidimensional Array as follows, but when I test it with alert() I get undefined. I would like to know how many items has the parent array (myArray), as I would ... More on stackoverflow.com
🌐 stackoverflow.com
javascript says array.length is undefined, but not the array - Stack Overflow
I'm trying to use information from the Politifact API by storing it in an array called "supperArray." I do so by calling the API three times, and pushing 10 values from each response to superArray,... More on stackoverflow.com
🌐 stackoverflow.com
September 3, 2018
🌐
EyeHunts
tutorial.eyehunts.com › home › javascript array length undefined | code
JavaScript array length undefined | Code
June 30, 2023 - Objects don’t have a length property, that way most time developers get JavaScript array length undefined error. A simple solution is, if you know you don’t have to worry about hasOwnProperty checks, would be to do this: ... A simple example code tries to get the length of an object and use it for..in the loop through the object and get values.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › length
Array: length - JavaScript - MDN Web Docs
The following example shortens the array numbers to a length of 3 if the current length is greater than 3. ... const numbers = [1, 2, 3, 4, 5]; if (numbers.length > 3) { numbers.length = 3; } console.log(numbers); // [1, 2, 3] console.log(numbers.length); // 3 console.log(numbers[3]); // undefined; ...
🌐
Medium
medium.com › @faheemkhan4865 › array-length-i-bet-youre-missing-something-961e7e70138e
Array.length: I bet, You’re missing something | by Faheemkhan | Medium
August 23, 2021 - Notice that elements in arr are undefined in middle. Because we had three elements earlier and after that we set the 6th element manually but didn’t set the 4th and 5th one. We can truncate or even empty our original array by setting array.length to a lower value. ... This means we are telling JS that we only want first 2 elements, so JS removes all other elements. ... const arr = [10,20,30]; arr.length = 2; console.log(arr) // [10, 20]// Making array emptyarr.length = 0; console.log(arr) // []
🌐
Krasimirtsonev
krasimirtsonev.com › blog › article › unexpected-usage-of-array-length
Unexpected usage of Array.length
For example: var str = 'Brown fox jump over the lazy dog'; function truncate (text, word) { var words = text.split(' '); var pos = words.indexOf(word); if (pos === -1) return text; words.length = pos; return words.join(' ') + ' ...'; } truncate(str, ...
🌐
MSR
rajamsr.com › home › javascript array length: how to use it effectively
JavaScript Array Length: How to Use It Effectively | MSR - Web Dev Simplified
January 31, 2024 - For example, you have an input email address and you want to extract the domain name from it. The @ delimiter can be used in combination with the JavaScript String split() method.
Find elsewhere
Top answer
1 of 7
15

Note: Array indexes are nothing but properties of Array objects.

Quoting MDN's Relationship between length and numerical properties section,

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's length property accordingly.

Quoting ECMA Script 5 Specification of Array Objects,

whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted

So, when you set a value at index 5, JavaScript engine adjusts the length of the Array to 6.


Quoting ECMA Script 5 Specification of Array Objects,

A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 232−1.

So, in your case 2 and 4 are valid indexes but only 2 is defined in the array. You can confirm that like this

arr.hasOwnProperty(2)

The other indexes are not defined in the array yet. So, your array object is called a sparse array object.

So why arr[2] is counted in for..in loop and not arr[4] is not counted?

The for..in enumerates all the valid enumerable properties of the object. In your case, since only 2 is a valid property in the array, it will be counted.

But, when you print arr[4], it prints undefined, because JavaScript will return undefined, if you try to access a property which is not defined in an object. For example,

console.log({}['name']);
// undefined

Similarly, since 4 is not yet defined in the arr, undefined is returned.


While we are on this subject, you might want to read these answers as well,

  • Why doesn't the length of the array change when I add a new property?

  • JavaScript 'in' operator for undefined elements in Arrays

2 of 7
9

There’s a difference between a property that has the value undefined and a property that doesn’t exist, illustrated here using the in operator:

var obj = {
    one: undefined
};

console.log(obj.one === undefined); // true
console.log(obj.two === undefined); // true

console.log('one' in obj); // true
console.log('two' in obj); // false

When you try to get the value of a property that doesn’t exist, you still get undefined, but that doesn’t make it exist.

Finally, to explain the behaviour you see: a for in loop will only loop over keys where that key is in the object (and is enumerable).

length, meanwhile, is just adjusted to be one more than whatever index you assign if that index is greater than or equal to the current length.

🌐
sebhastian
sebhastian.com › javascript-array-length
Understanding JavaScript array length property | sebhastian
July 6, 2022 - let students = ["Joseph", "Marco"]; students.length = 4; console.log(students); // output is ["Joseph", "Marco", undefined, undefined] If you push a new element into the array, it won’t replace the undefined elements.
🌐
Dustin John Pfister
dustinpfister.github.io › 2018 › 12 › 14 › js-array-length
Array length in javaScript and addressing the confusion | Dustin John Pfister at github pages
November 30, 2021 - For example if it is a Unit16Array and it has 3 elements the length of it is 3, and the byte length of it is 6. The length of an array generally refers to the number of elements, or the highest index value plus one.
Top answer
1 of 3
1

The reason is that you're not logging superArray in your fetch promise. If you add the call to console.log() in your last then() call it works. The reason for this is that fetch is executed asynchronously, which means that any additional code that comes after the fetch call is executed long before the fetch has returned anything.

The reason you can see a full log of superArray even when doing it outside the fetch is a special console behaviour.

const URL1 = "https://www.politifact.com/api/statements/truth-o-meter/people/barack-obama/json/?n=50";
const URL2 = "https://www.politifact.com/api/statements/truth-o-meter/people/hillary-clinton/json/?n=210";
const URL3 = "https://www.politifact.com/api/statements/truth-o-meter/people/bernie-s/json/?n=70";
var superArray = [];
fetch("https://cors-anywhere.herokuapp.com/" + URL1)
  .then(results => {
    return results.json();
  })
  .then(data => {
    data = data.filter(function(item) {
      return item.speaker.name_slug == "barack-obama" && item.statement_type.statement_type !== "Flip";
    });
    for (var i = 0; i < 10; i++) {
      superArray.push(data.splice(Math.random() * data.length, 1)[0]);
    }
  })
fetch("https://cors-anywhere.herokuapp.com/" + URL2)
  .then(results => {
    return results.json();
  })
  .then(data => {
    data = data.filter(function(item) {
      return item.speaker.name_slug == "hillary-clinton" && item.statement_type.statement_type !== "Flip";
    });
    for (var i = 0; i < 10; i++) {
      superArray.push(data.splice(Math.random() * data.length, 1)[0]);
    }
  })
fetch("https://cors-anywhere.herokuapp.com/" + URL3)
  .then(results => {
    return results.json();
  })
  .then(data => {
    data = data.filter(function(item) {
      return item.speaker.name_slug == "bernie-s" && item.statement_type.statement_type !== "Flip";
    });
    for (var i = 0; i < 10; i++) {
      superArray.push(data.splice(Math.random() * data.length, 1)[0]);
    }
    console.log(superArray[0]);
  })

2 of 3
0

It's possible to be logged into your console before data is fetched. To make it sure, log that after accomplishing the data ie. inside .then().

fetch(...)
.then(results => {...})
.then(data => {...})
.then(()=> console.log(superArr[0]))

Or, you may use:

superArray.length && console.log(superArray[0]);
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-cannot-read-property-length-of-undefined
Cannot read properties of undefined (reading 'length') in JS | bobbyhadz
Copied!const arr = ['bobby', 'hadz', 'com']; // ⛔️ TypeError: Cannot read properties of undefined (reading 'length') const result = arr[3].length; JavaScript indices are zero-based, so the first element in an array has an index of 0 and the last element has an index of array.length - 1. The last index in the array in the example is 2.
🌐
Reddit
reddit.com › r/learnjavascript › [deleted by user]
[deleted by user] : r/learnjavascript
July 15, 2022 - Line 208: The condition should be i < array.length -1. Line 209 will lead to the string variable being undefined, hence "length" is an invalid property. Change all your for loops to be the length - 1, to ensure you're not accessing an index that doesn't exist ... I learn JavaScript but then I forget it.
🌐
SmartBear Community
community.smartbear.com › smartbear community › testcomplete › testcomplete questions
Length of Array is returned as undefined | SmartBear Community
March 4, 2025 - function Test1() { var AppProcess = Sys["WaitProcess"]("AXISEL"); var ArrProps = new Array("Description","ObjectType"); var ArrVals = new Array("*Batch Name: GlaaS Post Job Submission*","ListItem"); var ListJob = AppProcess["FindAllChildren"](ArrProps,ArrVals,1000); var ArrLength1 = ListJob.length; var ArrLength = ListJob.Count; ListJob[ArrLength - 1].Click(); Delay(1000); } ... I haven't tested the code, but could you replace the code with this, to see if it logs the length of ListJob.
🌐
TrackJS
trackjs.com › javascript answers › how to fix `cannot read properties of undefined (reading 'length')`
How to fix `Cannot read properties of undefined (reading 'length')` • TrackJS
April 8, 2026 - Common JavaScript error when accessing length property on undefined values. Usually occurs with arrays, strings, or API responses that haven't loaded yet. Quick fixes: add null checks, use optional chaining, handle loading states.