Welcome to my blog where I write mostly about technical things!

Destructuring Tweets – Episode 9 – Short Read about Length

Welcome to my dev.to series about my takes on Social Media code challenges! This time it's going to be awesome. You will learn something about an API you use daily: length! You read that correctly. Length. Let's jump right in 👉

The Snippet

const numbers = ['100', '200'];
numbers.length = 0;


In that code, they initialize a constant with an array containing two strings – nothing special so far. However, in the next line, the property length gets overwritten by 0.
Just in case, length is a property holding the element count of an Array.

The length property of an object which is an instance of type Array sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

from MDN Array.prototype.length

Okay, so what we do here is replace the item count of 2 with a 0.
On the last line, the snippet logs the first element of the array to leave it up for us to guess the output.

The Output

The logged value is not exactly spectacular but may be somewhat counter-intuitive. You probably would expect the length to be read-only or have no significant effect on the calling instance, thus still logging 100.
However, in reality, that's not the case, and it is a tedious matter of undefined.

The Analysis

That's probably the most boring analysis in the existence of my blogging career yet. Cause the answer is that it's designed like that! The length can be overwritten and ditches any elements on indexes exceeding the given value.

Decreasing the length property does, however, delete elements.

from MDN Array

In our example, we provide the value of 0. The array is emptied and does not hold a single item anymore. When we call the first index (0), the value of undefined reflects precisely that.

Further Reading

Relationship between length and numerical properties
MDN Array Length Page
New in Firefox 23: the length property of an array can be made non-writable