This Week in JavaScript - 18 January 2016

The following is wrong:

What happen if we have four elements in the array and we set length to five:

var arr = [‘a’, ‘b’, ‘c’, ‘d’];
arr.length = 5;
arr; // [“a”, “b”, “c”, “d”, undefined]

The text below that code has been corrected but not the code (as an extra entry is not inserted and so the undefined should not be there. The array is actually now - [“a”, “b”, “c”, “d”,] - note the trailing comma.

Changing the length to a larger number does not create extra undefined elements. There is a BIG difference between elements in an array that are undefined and ones that don’t exist.

The author initially goes wrong with the statement:

We all know that while working with Arrays .length returns the number of the added items.

That of course is NOT what we all know as it is incorrect. Only those new to JavaScript might think that.

For the length to return the number of entries added you need to start with an empty array and add the elements without leaving any gaps.

The length is only automatically updated when you use one of the built in methods that adds or removes elements from the front or end of the array or you add an element beyond the end of what is currently in the array.

The length does not necessarily reflect the number of entries in the array.For example:

var a = new Array(5); // length = 5, entries = 0 [,,,,]
var b = ["a", "b", "c", "d"];
b[10] = 'e'; // length = 11, entries = 5 ['a','b','c','d',,,,,,,'e']

If the last statement above had been b.length = 10; then the only difference would be that the 11th entry containing ‘e’ would be missing and so the length would only be 10 (as set) and the number of entries 4.

The author of that article didn’t understand the difference between an undefined array entry and one that doesn’t exist and when that difference was pointed out to them only part of the article has been corrected.

About the only part of the article that was right before the attempt to correct it is that setting length to a lower value will remove entries from the end of the array (if they exist).

Where the author says:

Can we use the same technique to pull elements from the beginning of the array? The answer is yes. It’s ugly but it is possible:

There is no reason why you’d ever want to use the ugly code proposed when you can use shift() to remove one entry or splice() to remove as many as you want in a single call.

var arr = ['a', 'b', 'c', 'd'];
arr.splice(0,2); // now arr = ['c','d']

Array.prototype.length is misunderstood by most JavaScript beginners and that article doesn’t do much to help people understand it as the author appears to not understand it properly and has written the article when they discovered that the value is writable without having any further knowledge of how it works than that.