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 Overflowreaddir 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.
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);
});
}
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.
Console.log misleadingly says array.length = 0 - JavaScript - SitePoint Forums | Web Development & Design Community
javascript - Array/List length is zero but Array is not empty - Stack Overflow
javascript - Array length is zero but Array is not empty - Stack Overflow
Javascript: Array is not empty but size is 0 - Stack Overflow
For anyone else who is facing similar issue:
You are very likely populating the array within an asynchronous function.
function asyncFunction(list){
setTimeout(function(){
list.push('a');
list.push('b');
list.push('c');
console.log(list.length); // array length is 3 - after two seconds
}, 2000); // 2 seconds timeout
}
var list=[];
//getting data from a database
asyncFunction(list);
console.log(list.length) //array is length zero - after immediately
console.log(list) // console will show all values if you expand "[]" after two seconds
__proto__ is not your object, it is the accessor for the prototype.
The
__proto__property ofObject.prototypeis an accessor property (a getter function and a setter function) that exposes the internal[[Prototype]](either an object ornull) of the object through which it is accessed.The use of
__proto__is controversial, and has been discouraged.
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 :)
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.
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
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.
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.
This is due to the asynchronous nature of execution of the code. The subscribe method accepts a callback, which is the arrow function that you have written with the parameter named response.
So, the callback will not be executed immediately but will be done after a while. But, since JS is asynchronus, it wouldn't wait for the callback to get executed and will move on to the next line of the code where the variable will still be an empty array.
As suggested in the other answers, you could put the console log within the callback function to log the expected value.
You are doing console.log before getting response in subscribe. Just move console.log inside subscribe.
var objects = [];
this.get().subscribe(
response => {
for (var i = 0; i < response.length; i++) {
objects.push(response[i]);
}
console.log(objects.length);
}
);
When you output an object with console.log its state may evolve and you are not necessarily seeing the state of this object at the time console.log was called but only at the time it was expanded in the console view. Which is not the case with primitives.
Most probable scenario: when calling console.log the array was empty, with a length of 0. When you expand the Array log in the console view you will see it populated even if it was not at the time it was logged.
I did the same test and it works correctly on my computer, it logs length as 1. Maybe there is something else in your code that is causing a side effect
Your are define A is array .Array is not key and value pair,Object only have key value pair
Check the console.log A its still empty
var A = [];
A['key1'] = 'apple';//its not added because is a array
console.log(A);
console.log(A.length);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
If you need to add key value pair Define A as a Object.and find the length using Object.keys(A) .It will create array of the Object keys
var A = {};
A['key1'] = 'apple';
console.log(A);
console.log(Object.keys(A).length);
console.log(A.key1.length)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Better see the Difference between an array and an object?
You are using javascript associative array which don't have the built-in function like length to get the number of properties in the array. So Instead of using length function you can use the following line to get the number of properties in the array.
Object.keys(A).length