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.

Answer from ibrahim mahrir on Stack Overflow
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);
    });
}
🌐
Reddit
reddit.com › r/reactjs › console.log(array.length) gives 0 even though array has 6 nums(in render())??
r/reactjs on Reddit: console.log(array.length) gives 0 even though array has 6 nums(in render())??
October 27, 2020 -

hi i have this empty array which i pushed 6 numbers from 6 loops but when i try to get the array length in render, it gives back 0. Why is this so?

this is my function displayPokemons(ids) {
this.setState({txtStatus: "5"})
var results = [];
for (let id of ids) {
console.log("aa" + id);
this.getPokemonDetails(id).then(function(id) {
results.push(id)
})
this.setState({displayedPokemons2: results})
}}

and then in render
render() {

{console.log(this.state.displayedPokemons2)}
{console.log(this.state.displayedPokemons2.length)}

}

{console.log(this.state.displayedPokemons2)} gives me the 6 elements in the array
but {console.log(this.state.displayedPokemons2.length)} gives me 0.

Discussions

Console.log misleadingly says array.length = 0 - JavaScript - SitePoint Forums | Web Development & Design Community
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 More on sitepoint.com
🌐 sitepoint.com
0
May 2, 2016
javascript - Array/List length is zero but Array is not empty - Stack Overflow
I see that __proto__: Array(0) and I'm assuming this means it's a 0 length Array but how do I make it non-zero length so that I can iterate through it? More on stackoverflow.com
🌐 stackoverflow.com
javascript - Array length is zero but Array is not empty - Stack Overflow
When I'm trying to iterate through an array, get it's length or access indexes I'm getting Error TypeError: Cannot read property 'map' of undefined. The array isn't empty and when I console.log() i... More on stackoverflow.com
🌐 stackoverflow.com
Javascript: Array is not empty but size is 0 - Stack Overflow
I create a array in Javascript. I want to use the array for key-value pair. I can successfully add new items and delete items but the length of it is always 0. Actually the problem I faced is when I want to convert it to a JSON string, it shows empty string: "[]". More on stackoverflow.com
🌐 stackoverflow.com
May 23, 2017
🌐
freeCodeCamp
freecodecamp.org › news › check-if-javascript-array-is-empty-or-not-with-length
How to Check if a JavaScript Array is Empty or Not with .length
October 5, 2020 - Because arr.length is 0, or false, it returns true. Let's use this with an if statement, and print out a message if our array is empty. When checking if an array is empty or not, it's often best to also check if the array is indeed an array. ... Because there might be the case when you were expecting to check the length of an array, but ...
🌐
YouTube
youtube.com › codeignite
javascript array length 0 but not empty - YouTube
Get Free GPT4o with 1 million code snippet from https://codegive.com in javascript, the `length` property of an array indicates the number of elements in th...
Published: June 15, 2024
Views: 32
🌐
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
🌐
Stack Overflow
stackoverflow.com › questions › 64688504 › array-length-is-zero-but-array-is-not-empty
javascript - Array length is zero but Array is not empty - Stack Overflow
It worked, but I immediately got the similar error. useEffect(() => { (async() => { await blog.authors.map(data => { console.log(data) }) })() }, [blog]) ... __proto__: Array(0) means the object inherits from Array.prototype which is an empty array.
Find elsewhere
🌐
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. For ex, if we say arr.length= 2 · This means we are telling JS that we only want first 2 elements, so JS removes all other elements. arr.length = 0 // this makes the arr empty ·
🌐
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 - If I then set the length of the array back to a higher value then that of the current length of 1, lets say 5, then the result is a sparse array. The array is sparse because the length of the array is 5, but it is now only element index 0 that ...
🌐
Flexiple
flexiple.com › javascript › check-if-array-empty-javascript
How to check if an array is empty using Javascript? - Flexiple
March 10, 2022 - If the length of the array is 0, then the array is empty otherwise it is not empty. One obvious question we might have is why not just use the length property at the beginning itself?
Top answer
1 of 3
5

This is happening because you are not awaiting the service. What happens is that the data has not come from the server and u are console logging its value.

let fetchData=async (params:any)=>{
    this.booksInCheckout = await this.checkoutService.getCheckoutBooks();// getting array value service
    //other code here
}

async function fetchData( params:any)=>{
    this.booksInCheckout = await this.checkoutService.getCheckoutBooks();// getting array value service
    //other code here
}

use one of the below mentioned function implementation for your service.

//code for service 
 function getCheckoutBooks(){
return http.get();
}


 
async function getCheckoutBooks(){
const booksData : any = await http.get();

return booksData;
}

The following code should work.

ngOnInit() {
   this.checkoutService.getCheckoutBooks().subscribe((booksInCheckout)=>{
    console.log(booksInCheckout); // for array
    console.log(booksInCheckout.length); // for length of array
    console.log(booksInCheckout[0]); // for first element
  
  });

}

You are facing this problem beacuse you are calling an asynchronous function but due to the asynchronous nature of javascript, the code below the function gets executed before the asynchronous task completes.

So here i have added a callback for the asynchronous task. Hope it helps :)

2 of 3
1

The reason is - Because your method this.checkoutService.getCheckoutBooks() is asynchronous in nature and you are trying to console before the data is fetched actually.

this.booksInCheckout = this.checkoutService.getCheckoutBooks();// Async Call

To sort out this problem either use subscribe to deal with async call or you can use console within the getCheckoutBooks method or maybe async in template side too.

🌐
Reddit
reddit.com › r/learnjavascript › !! vs ==0 when checking if array is empty
r/learnjavascript on Reddit: !! vs ==0 when checking if array is empty
June 30, 2024 -

I have an array in a function and I want the function to return true/false depending on if the array is empty (return true if not empty and vice versa)

I have narrowed down the condition to these 2 possible return statements. Which one is preferred?

return result.recordset.length == 0

return !!result.recordset.length
Top answer
1 of 3
116

foo = [] creates a new array and assigns a reference to it to a variable. Any other references are unaffected and still point to the original array.

foo.length = 0 modifies the array itself. If you access it via a different variable, then you still get the modified array.

Read somewhere that the second one creates a new array by destroying all references to the existing array

That is backwards. It creates a new array and doesn't destroy other references.

var foo = [1,2,3];
var bar = [1,2,3];
var foo2 = foo;
var bar2 = bar;
foo = [];
bar.length = 0;
console.log(foo, bar, foo2, bar2);

gives:

[] [] [1, 2, 3] []

arr.length =0;// expected to empty the array

and it does empty the array, at least the first time. After the first time you do this:

arr = arr + $(this).html();

… which overwrites the array with a string.

The length property of a string is read-only, so assigning 0 to it has no effect.

2 of 3
3

The difference here is best demonstrated in the following example:

var arrayA = [1,2,3,4,5];

function clearUsingLength (ar) {
    ar.length = 0;
}

function clearByOverwriting(ar) {
    ar = [];
}

alert("Original Length: " + arrayA.length);
clearByOverwriting(arrayA);
alert("After Overwriting: " + arrayA.length);
clearUsingLength(arrayA);
alert("After Using Length: " + arrayA.length);

Of which a live demo can be seen here: http://www.jsfiddle.net/8Yn7e/

When you set a variable that points to an existing array to point to a new array, all you are doing is breaking the link the variable has to that original array.

When you use array.length = 0 (and other methods like array.splice(0, array.length) for instance), you are actually emptying the original array.

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › check-if-an-array-is-empty-or-not-in-javascript
Check if an array is empty or not in JavaScript - GeeksforGeeks
July 11, 2025 - let a = []; if (Array.isArray(a) && a.length === 0) { console.log("Empty"); } else { console.log("Not Empty"); }