Only numeric indices affect the .length of an Array.

Other named properties are allowed, but they aren't the typical use for an Array object. By using "", you're creating a non-numeric property on the object. You can access it like this:

errors[""];

But you can't get to it with the typical Array methods.


For named properties, you'd typically use an Object instead. Either way, you can get a count of the number of own, enumerable properties (including numeric indices) by using Object.keys().

Object.keys(errors).length;
Answer from cookie monster on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 38426536 › simple-array-length-always-0-even-if-content-present
javascript - Simple Array Length -always 0 even if content present - Stack Overflow
Anyway, I think you'll find the array is empty at the time you log it, but that it has data by the time you expand it in the console. (If you log JSON.stringify(markersToPush) that would confirm it.) You are calling an asynchronous function, geocoder.geocode(), and the callback function you pass to it won't be called with the data until after the loop ends and after the console.log() statements. See this question. ... You don't seem to be outputting the length property but rather the size property.
Discussions

brackets - JavaScript array.length remains 0 after elements been pushed in - Stack Overflow
Im writing a brackets validation function, and seems like under some conditions the tmpStack.length remains 0 even after some elements been pushed in. For normal input like "[(1+2)]"or "[(1+2]" the function works, but for input such as "[12" it doesnt, for the reason that tmpStack.length remains 0. More on stackoverflow.com
🌐 stackoverflow.com
javascript - Array length remains 0 even though I push 'objects' to it - Stack Overflow
I put in comments where the error is. serverItems.length is 0 even though when debugging in a browser in the DOM tree it has an array serverItems with all the data inside. Assumingly this serverItems is in another scope and not the one I am calling when I want to get the length? More on stackoverflow.com
🌐 stackoverflow.com
August 9, 2014
javascript - Array.length reading 0 after pushing objects on array - Stack Overflow
I'm trying to push objects on to array and process the array as a queue. Nothing is currently removing anything from the array, and each time the acme.addToValidateQueue function is called ( several More on stackoverflow.com
🌐 stackoverflow.com
jquery - incorrect array length after using array.push() in JavaScript - Stack Overflow
Fellow noob in JavaScript so forgive me if I'm missing something basic. I have an array that I want to push data retrieved from an AJAX request using JQuery, where CalendarEvent is a custom class I More on stackoverflow.com
🌐 stackoverflow.com
November 28, 2019
🌐
Stack Overflow
stackoverflow.com › questions › 54545726 › didnt-change-the-length-of-array-after-push-in-javascript
Didn't change the length of Array after push in JavaScript - Stack Overflow
June 2, 2019 - I have a feeling that this is the result of confusion around asynchronous code. Most likely, at the moment console.log(buildsArray) runs, the array actually is empty, but by the time you expand that line in the console, new items have been pushed to it.
🌐
Stack Overflow
stackoverflow.com › questions › 28003877 › javascript-array-length-remains-0-after-elements-been-pushed-in
brackets - JavaScript array.length remains 0 after elements been pushed in - Stack Overflow
Copyfunction validator(str){ var tmpStack = []; for (var i = 0; i < str.length; i++) { if (str[i].match(/\[|\{|\(/)) { tmpStack.push(str[i]); } else if ( (str[i]=="]" && tmpStack.pop()!="[") || (str[i]=="}" && tmpStack.pop()!="{" ) || (str[i]==")" && tmpStack.pop()!="(") ) { console.log("dis-match found for: " + (str[i])); return false; } } return !tmpStack.length; } var tstStr="[+]()1"; console.log(validator(tstStr));
🌐
Stack Overflow
stackoverflow.com › questions › 59080905 › incorrect-array-length-after-using-array-push-in-javascript
jquery - incorrect array length after using array.push() in JavaScript - Stack Overflow
November 28, 2019 - When I console.log(events) outside of the method (nothing else added or subtracted), the length is 0 and all my objects are inside an empty array. The first 2 lines in screenshot are console.log(events) outside the method, the second 2 lines are inside the method (I also don't know why they aren't showing in order). Can anyone help me fix my problem? ... In javascript all methods regular methods are called BEFORE any async code so what is happening is that your console log outside the code is happening BEFORE the method is ran, run any code that depends on the information in the ajax call inside of the method OR you can wrap any functions you need ran after that by using setTimeout().
Find elsewhere
🌐
SitePoint
sitepoint.com › javascript
Console.log misleadingly says array.length = 0 - JavaScript - SitePoint Forums | Web Development & Design Community
May 2, 2016 - Hi, please have a quick look at this CodePen: When I console.log() the length of the array, it returns 0 … even though I can iterate through the array. Why is that? Kind regards Thomas
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › push
Array.prototype.push() - JavaScript - MDN Web Docs
July 12, 2026 - Instead, we store the collection on the object itself and use call on Array.prototype.push to trick the method into thinking we are dealing with an array—and it just works, thanks to the way JavaScript allows us to establish the execution context in any way we want. ... const obj = { length: 0, addElem(elem) { // obj.length is automatically incremented // every time an element is added.
🌐
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 - The array is sparse because the length of the array is 5, but it is now only element index 0 that is defined, the remaining elements are not event undefined then are not defined, and as such they are just empty element locations. To get a better idea of why this will cause problems try using an array prototype method such as the array for each method, and see what happens. The result will be that the array for each method will not call the function it is given for any and all empty element locations. So in javaScript Arrays are created with the Array constructor, or more often the Array literal syntax.
Top answer
1 of 2
45

readdir is asynchronous. It won't get the results right away. You should use the filePaths inside the callback. The only reason why the console shows the value is because the console evaluates the array when you unfold it.

When you press the little arrow on the left, put the mouse on the i box on the right. What happens is that the console keeps a reference to the array, so when the user unfolds the array it then shows the current value of the array. But when you log filePaths.length the array is empty because readdir didn't finish reading yet, that's why you get 0. But by the time you open the console and press that arrow, readdir will have already done reading and the console will print the current value of the array (after it's been filled).

Example to demonstrate the problem: (not a solution, it's just to understand what is really happening)

Open the browser console and try this code and see what happens:

var arr = [];

setTimeout(function() {
  arr.push(1, 2, 3);
}, 5000);

console.log(arr.length);

console.log(arr);

Here the array and it's length are both logged before the array is filled. The array will be filled after 5 seconds. So the output will be 0 and a string representation of the array array[]. Now because arrays could have tons of data, the console won't show that data until the user unfolds the array. So what the console does is keep a reference to the array until the user press the unfold arrow. If you unfold the array before 5 seconds you'll see that the array is empty (not filled yet). If you wait until the 5 seconds pass then unfold it, then you'll see that it's filled, even though it was logged as an empty array.

Note: Also, the line that get logged to the console (something like > Array(0)) is just a string representation of the object/array at the moment the log happens. It won't get updated if the object/array changes. So that also may seem confusing sometimes.

I hope it's clear now.

2 of 2
1

Just to expand on @ibrahim-mahrir 's answer, they means like this

function getPaths() {
    var dirPath = document.getElementById("mdir").innerHTML;
    var filePaths = [];
    fs.readdir(dirPath, function(err, dir) {
        for (var i = 0, l = dir.length; i < l; i++) {
            var filePath = dir[i];
            filePaths.push(dirPath + "/" + filePath);
        }
        console.log(filePaths);
        console.log(filePaths.length);
    });
}
🌐
Stack Overflow
stackoverflow.com › questions › 52662030 › js-array-length-returns-0
javascript - JS array length returns 0 - Stack Overflow
When I try to access the values or array data, for example, console.log(checkState.length);, I get 0. What am I doing wrong here? ... Copy function firstFunction() { var array = []; var url3 = "/Home/CheckPrintService?printer=" + document.getElementById("printerName").value; $.get(url3, null, function (data3) { $("#msgPrinterName").html(data3); var str = $("#msgPrinterName")[0].innerText.toString(); if (str.includes("ERROR CODE")) { array.push(str); } //console.log($("#msgPrinterName")[0].innerText.toString()); }); var e = document.getElementById("ddlViewBy"); var deviceType = e.options[e.sele
🌐
Stack Overflow
stackoverflow.com › questions › 73325253 › why-variable-with-length-of-array-in-it-doesnt-change-after-push
javascript - Why variable with length of array in it doesn't change after push? - Stack Overflow
0 · why the arrLength variable ... at 18:20 · GreenLightGreenLight · 133 bronze badges 2 · 2 · Because you set arrLength before changing the array's size....
🌐
Reddit
reddit.com › r/learnjavascript › array length 0 even though items are present
r/learnjavascript on Reddit: array length 0 even though items are present
October 18, 2021 -
let raw='https://raw.githubusercontent.com/nshntarora/Indian-Cities-JSON/master/cities.json'

var cities=[]

fetch(raw) //getting the rawdata from the url
.then(response=>response.json()) // returned data is parsed as json file
.then(data=>data.forEach(item=>cities.push(item))) //in the json data, each is pushed into cities

console.log(cities[0]);//undefined

i am trying to get cities objects in the cities array and try to filter through them. however, whenever i am pushing them to the array, im getting the following output when i console.log(cities):

[]
0: {id: '1', name: 'Mumbai', state: 'Maharashtra'}
1: {id: '2', name: 'Delhi', state: 'Delhi'}
2: {id: '3', name: 'Bengaluru', state: 'Karnataka'}
3: {id: '4', name: 'Ahmedabad', state: 'Gujarat'}
4: {id: '5', name: 'Hyderabad', state: 'Telangana'}
5: {id: '6', name: 'Chennai', state: 'Tamil Nadu'}
6: {id: '7', name: 'Kolkata', state: 'West Bengal'}
7: {id: '8', name: 'Pune', state: 'Maharashtra'}
8: {id: '9', name: 'Jaipur', state: 'Rajasthan'}
9: {id: '10', name: 'Surat', state: 'Gujarat'}
10: {id: '11', name: 'Lucknow', state: 'Uttar Pradesh'}
11: {id: '12', name: 'Kanpur', state: 'Uttar Pradesh'}
12: {id: '13', name: 'Nagpur', state: 'Maharashtra'}
13: {id: '14', name: 'Patna', state: 'Bihar'}
14: {id: '15', name: 'Indore', state: 'Madhya Pradesh'}
15: {id: '16', name: 'Thane', state: 'Maharashtra'}
16: {id: '17', name: 'Bhopal', state: 'Madhya Pradesh'}
17: {id: '18', name: 'Visakhapatnam', state: 'Andhra Pradesh'}
18: {id: '19', name: 'Vadodara', state: 'Gujarat'}
19: {id: '20', name: 'Firozabad', state: 'Uttar Pradesh'}
20: {id: '21', name: 'Ludhiana', state: 'Punjab'}
21: {id: '22', name: 'Rajkot', state: 'Gujarat'}
22: {id: '23', name: 'Agra', state: 'Uttar Pradesh'}
23: {id: '24', name: 'Siliguri', state: 'West Bengal'}

why am i not able to access the items if they are already present?