DEV Community

Cover image for Destructuring Tweets - Episode 9 - Short Read about Length
Kai
Kai

Posted on

Destructuring Tweets - Episode 9 - Short Read about Length

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 👉👉👉

Snippet of the Week

This week's snippet is from Apoorv Tyagi:

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

console.log(numbers[0]);
Enter fullscreen mode Exit fullscreen mode

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 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 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 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.

Snippet Summary

Top comments (0)