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.
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.
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;
Because that is not how you add an item since Arrays only accept numeric keys. You do it like this:
errors.push("blah"); /*or*/ errors[0] = "blah";
//Now if you check the length:
errors.length; //1
Also, if you are using it as an Object, '' isn't a valid name either.
*Correction: Looks like you can use "" (empty string) as a key.
console.log(array.length) gives 0 even though array has 6 nums(in render())??
Javascript array length of 0 - Stack Overflow
JavaScript Array.length returning 0 - Stack Overflow
javascript - What's array.length >>> 0; used for? - Stack Overflow
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 is not synchronous.
Your console.log statements appear after you have called getTrips but before the getTrips callback has fired.
Effectively, you are trying to return the response from an asynchronous call.
response is an object. Objects in JS are always referenced. You are logging that reference, and then the object gets updated with the new values (and the new length) when the getTrips callbacks fire. The new object is reflected in the console.
response.length is a number. You are logging it. Number values are not references. It is 0 because at the time you called console.log it was 0. The display doesn't update when the value changed because is a number and not an object.
So what actually happens is that when you log your response it actually having length as 0. But after the asynchronous response is returned it has 42 items but length being a property is logged as number. But your response being an object is logged initially with zero items. But when the actual response is received the reference to the response object is updated and you see that the response is having 42 items and length is also 42. The below code is an example for that that to show after the setTimeout is called the logged response is updated in the console.
var getTopSelection = function(callback) {
var topSelection = [];
markers=[1,2,3,4,5,6,7,8,9];
for(var i=0; i < markers.length; i++) {
if(markers[i].map !== null) {
var stationID = markers[i].id;
getTrips(stationID, function(response) {
topSelection.push({
StationID: i,
Trips: response
});
}, function(error) {
console.log(error);
})
}
}
callback(topSelection);
};
function getTrips(station,fun){
setTimeout(function(){
fun(["trip1","trip2","trip3"]);
},1000)
}
getTopSelection(function(response) {
console.log(response); //115
console.log(response.length); //116
})
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Try executing this snippet(have modified accordingly to show what actually happens) in a Fiddle here. And observe the output in console as in stackoverflow snippet result it wont be visible. Here is snap of the Console Output

Hope it helps :)
You can use length property only if array contains elements associated with indexes. If it is associative array then length property will return 0. You can count elements by yourself using this code:
function len(arr) {
var count = 0;
for (var k in arr) {
if (arr.hasOwnProperty(k)) {
count++;
}
}
return count;
}
Then you can count elements of "mappings" array using len(mappings)
JavaScript arrays does not work like those in for instance PHP which can work as associative arrays. However, due to JavaScript's dynamic nature, and the fact that an Array is a subclass of Object, you can still attach arbitrary properties on to a Array. The length property will however not reflect this (as you have discovered).
If you're using newer browsers/polyfills (like core-js), I recommend going with Map instead (Documentation). Otherwise, use a simple object ({}), and use Object.keys on the object to get the keys.
Example of the later:
var mappings = {};
mappings['foo'] = 'bar';
Object.keys(mappings); // returns ['foo']
mappings[Object.keys(mappings)[0]]; // returns 'bar'
// Loop through all key-value pairs
Object.keys(mappings).forEach(function(key) {
var value = mappings[key];
// Do stuff with key and value.
});
This seems to be the safest way to ensure length is a non-negative (32-bit) integer.
Just another example of where JavaScript lacks proper standard functions, this time for save conversion of unknown types into, well, 32-bit unsigned integers.
>>> is the bitwise "zero-fill right shift" operator.
JavaScript numbers can represent both integers and floating point numbers. Sometimes you only want an integer. Any positive JavaScript Number representing a number less than 2^32 will be rounded down (truncated, as in Math.floor) to the nearest integer. Numbers ≥ 2^32 are turned to 0. Numbers less than 0 will turn into a positive value (thanks to the magic of two's-complement representation).
However, this.length would presumably ALWAYS be an integer less than 2^32…so I can't explain why the code would be doing that. The result should be the same as this.length.
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);
}
);
Is there any difference between checking an array's length as a truthy value vs checking that it's > 0?
Since the value of arr.length can only be 0 or larger and since 0 is the only number that evaluates to false, there is no difference.
In general, Boolean(n) and Boolean(n > 0) yield different results for n < 0.
In other words is there any reason to use one of these statements over the other
Only reasons related to code readability and understanding, not behavior.
array.length is fastest and shorter than array.length > 0. You can see difference of their speeds : http://jsperf.com/test-of-array-length
if(array.length){...} is similar to if(0){...} or if(false){...}
For the first time after years of working with JS, I've seen something like this:
var a = [1,2,3]; a.length = 0; a // []
Does someone know how it works internally? I find this behaviour quite strange.