Wad up? Welcome to my dev.to series about my takes on Twitter code challenges! This time it's going to be awesome. You will learn something about an API you use on a daily basis: length! You read that correctly. Length. Let's jump right in 👉👉👉
const numbers = ['100', '200']; numbers.length = 0; console.log(numbers);
In that piece of 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
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.
Okay, so what we do here is replacing 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 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
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.
- Trickery: special behavior of overwriting length
- Key Learning: the length property of an array is not read-only and heavily influences the calling instance
- Further Reading: