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.

Answer from Quentin on Stack Overflow
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.

Discussions

console.log(array.length) gives 0 even though array has 6 nums(in render())??
Show the code Holmes More on reddit.com
🌐 r/reactjs
5
1
October 27, 2020
Javascript array length of 0 - Stack Overflow
I am getting some weird behaviour with the following, it shows an array length of 0 eventhough printing it right before that shows that there clearly is a length greater than 0: var getTopSelection = More on stackoverflow.com
🌐 stackoverflow.com
June 8, 2017
JavaScript Array.length returning 0 - Stack Overflow
I have javascript Array that looks like The problem is Object.mappings has 3 elements which are clearly printed in console with console.log(), but when I try to find length of the array it return... More on stackoverflow.com
🌐 stackoverflow.com
March 30, 2016
javascript - What's array.length >>> 0; used for? - Stack Overflow
Possible Duplicates: 1. What good does zero-fill bit-shifting by 0 do? (a >>> 0) 2. JavaScript triple greater than I was digging through some MooTools code, and noticed this snippet being use... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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
🌐
EyeHunts
tutorial.eyehunts.com › home › javascript array length 0 | zero check and set array examples
JavaScript array length 0 | Zero Check and set Array examples
November 30, 2021 - The way to empty an array is to set its length to zero. <!DOCTYPE HTML> <html> <body> <script> var arr1 = [1, 2, 3, 5, 2, 8, 9, 2]; arr1.length = 0; console.log(arr1); </script> </body> </html>
🌐
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.

🌐
Kevin Chisholm
blog.kevinchisholm.com › javascript › javascript-array-length-always-one-higher
Why is a JavaScript array length property always one higher than the value of the last element's index? | Kevin Chisholm - Blog
February 10, 2021 - Home › JavaScript › Why is a JavaScript Array Length Property Always One Higher Than the Value of the Last Element’s Index? Arrays in JavaScript are zero-based. This means that JavaScript starts counting from zero when it indexes an array.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array
Array - JavaScript - MDN Web Docs
July 28, 2026 - The length property is converted to an integer and then clamped to the range between 0 and 253 - 1. NaN becomes 0, so even when length is not present or is undefined, it behaves as if it has value 0. The language avoids setting length to an unsafe integer. All built-in methods will throw a ...
🌐
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.
Find elsewhere
🌐
C# Corner
c-sharpcorner.com › blogs › array-vs-arraylength-0
array = [] vs. array.length = 0
February 7, 2021 - In this short blog post, we'll understand the difference between the two ways of emptying an object in JavaScript i.e. by assigning an empty array and setting the length property of an array to zero.
Top answer
1 of 3
4

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.

2 of 3
1

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 :)

🌐
MeasureThat
measurethat.net › Benchmarks › Show › 14491 › 0 › arraylength-vs-arraylength-0
Benchmark: array.length vs array.length > 0 - MeasureThat.net
`Array.slice(-1)[0]` vs `Array[Array.length]` for 10000 length · JS array emptiness check · array.splice vs array.length · arr.at(-1) vs arr[arr.length - 1] array.length = 0 vs [] Comments · Do you really want to delete benchmark?
🌐
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 - With the operator added, it will return true if its operand is false. 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.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript array methods › javascript array length
JavaScript Array Length Property
November 4, 2024 - By changing the value of the length property, you can remove elements from an array or make an array sparse. If you set the length property of an array to zero, the array will be empty: const fruits = ['Apple', 'Orange', 'Strawberry']; fruits.length ...
🌐
Mimo
mimo.org › glossary › javascript › array-length
JavaScript Array Length: Master Data Handling
Setting it to a smaller number truncates the array, and setting it to 0 is an effective way to clear it completely. Zero-Based Indexing: The length is always one greater than the index of the last element (lastIndex = length - 1). It Measures Size, Not Data: An array can have a length but contain ...