Truncate or empty an array with length in JavaScript
Intermediate · 3 min read
Every array has a length, and most people only ever read it. But you can also set it. Making length smaller chops items off the end, and setting it to 0 empties the array. You will see xs.length = 0 in real code for clearing a list that other parts of a program are also looking at, such as a shopping cart or a queue of jobs.
In this tutorial you will shorten an array, grow one, and empty one in place. Then you will look closely at the new slots a longer length creates, because they are not what they seem. You should know what an array and an index are. The rest is explained as we go.
What length really is
length is not a count of the items. It is one more than the highest index. Usually those are the same thing, but not always:
const sparse = [];
sparse[9] = 'x';
console.log(sparse.length); // 10
console.log(Object.keys(sparse)); // [ '9' ]
Only one item is stored, at index 9, yet length is 10. Object.keys lists the indexes that really hold something.
Holes
The empty places in that array, indexes 0 to 8, are called holes. Reading one gives undefined, but nothing is stored there. The in operator tells the difference: i in xs is true only if something is stored at index i.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
8 length is a property you can assign to
fairlength is not read-only. Truncate an array by shortening it, grow one by lengthening it, and empty one in place. Then look at what the grown slots contain.
Stuck? Three hints, smallest first
- 1. Assigning a smaller
lengthdeletes the elements past it, permanently. - 2.
xs.length = 0empties an array in place, which every other reference to it sees. - 3. Assigning a larger
lengthadds holes, notundefinedvalues.index in xstells them apart.
Step 1: shorten an array
Set length to a smaller number and the items past it are deleted.
const cut = [1, 2, 3, 4, 5];
cut.length = 3;
console.log(cut); // [ 1, 2, 3 ]
console.log(cut[4]); // undefined
Setting length back to 5 would not bring 4 and 5 back. They are gone for good. This is quicker than slice when you don't need the original any more, because it doesn't build a copy.
Step 2: grow an array
Set length to a bigger number and the array reports the new size.
const grown = [1, 2];
grown.length = 4;
console.log(grown.length); // 4
console.log(grown[3]); // undefined
console.log(3 in grown); // false
It looks like we added two undefined values. We didn't. 3 in grown is false: the two new slots are holes. That matters because map, forEach and filter skip holes, so a loop over this array would only ever visit 1 and 2.
Step 3: the wrong way to empty a shared array
Say two variables point at the same array. This often happens without you noticing: you pass an array into a function, or two parts of an app keep the same list.
let cart = ['rice', 'beans'];
const sameCart = cart;
cart = [];
console.log(cart); // []
console.log(sameCart); // [ 'rice', 'beans' ]
cart = [] doesn't empty anything. It makes a brand new empty array and points cart at it. sameCart still points at the old one, items and all.
Step 4: empty it in place
length = 0 deletes every item from the array itself, so every variable pointing at it sees the change.
const original = [1, 2, 3];
const alsoOriginal = original;
original.length = 0;
console.log(original); // []
console.log(alsoOriginal); // []
Both are empty, because there was only ever one array. Notice original can be const: const stops you pointing the name at a new array, but it doesn't stop you changing the array's contents.
Step 5: a length that makes no sense
length must be a whole number from 0 upwards.
try {
const a = [1];
a.length = -1;
console.log('accepted');
} catch (e) {
console.log(e.constructor.name); // RangeError
}
A negative length is refused with a RangeError, the built-in error for "number out of range".
The full solution
The panel truncates, grows, empties a shared array in place, builds a sparse array and tries a negative length. Press Run and look at the line that asks whether index 3 is present.
const cut = [1, 2, 3, 4, 5];
cut.length = 3; // the last two are gone for good
const grown = [1, 2];
grown.length = 4; // two holes appended
// Emptying in place, which every reference sees. Reassigning to [] does not.
const original = [1, 2, 3];
const alsoOriginal = original;
original.length = 0;
// A sparse array from a far-off index.
const sparse = [];
sparse[9] = 'x';
const badLength = (() => {
try { const a = [1]; a.length = -1; return 'accepted'; } catch (e) { return e.constructor.name; }
})();
console.log('truncated :', cut);
console.log('grown :', grown, 'length', grown.length);
console.log('is index 3 present?', 3 in grown, '<- a hole');
console.log('emptied in place:', original, 'and the other reference:', alsoOriginal);
console.log('sparse : length', sparse.length, 'but real keys', Object.keys(sparse));
console.log('length = -1:', badLength);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a shorter length truncates', cut, [1, 2, 3]);
test('the removed elements are unrecoverable', cut[4], undefined);
test('a longer length reports the new size', grown.length, 4);
test('but the added slots are holes, not undefined values', 3 in grown, false);
test('length = 0 empties in place', original, []);
test('which every other reference sees', alsoOriginal.length, 0);
test('length is one past the highest index', sparse.length, 10);
test('even though only one element exists', Object.keys(sparse), ['9']);
test('a negative length is refused', badLength, 'RangeError');
An array's length is defined as one past its highest index, and it is writable. That gives two idioms worth knowing: xs.length = 0 empties an array in place, which matters when other code holds the same reference — xs = [] would leave those references pointing at the old contents — and xs.length = n truncates without building a copy the way slice would.
Growing is the part that surprises. The new slots are holes: length counts them, Object.keys does not, and map will skip straight over them. Exercise 45 pursues that.
Common mistakes
- Expecting a longer length to add
undefinedvalues. It adds holes, whichmapandforEachskip. Usefillorpushif you need real values. - Writing
xs = []to clear a shared array. Other references keep the old contents. Usexs.length = 0. - Shortening an array you still need. The removed items can't be recovered. Use
xs.slice(0, n)to get a shorter copy instead.
Try it yourself
- Keep only the first two items of
['a', 'b', 'c', 'd']by settinglength. - Write
clear(list)that empties an array in place, and show that the caller's array is empty afterwards. - Make
[1, 2], setlengthto 4, then callfill(0). Is3 inthe array nowtrue?