Empty an array
Remove every item in place, so all references see an empty array.
function empty(values) { values.length = 0; return values; }
Usage
const queue = ['ana@example.com', 'rui@example.com'];
const sameQueue = queue;
empty(queue);
sameQueue.length; // → 0
let list = [1, 2];
const alias = list;
list = [];
alias; // → [1, 2]
Know the limits
- Setting length mutates the array. Assigning [] only rebinds one variable, as the second example shows.
- The original returned 0, the assigned length; this version returns the array.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Empty an array from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Returns the emptied array instead of 0. Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Original source commit: 14b481cf60df. This edition’s file: contents/empty-an-array.mdx in akamind/1loc, commit 0a77f131b22d. Read the license.
Keep exploring
- Clone an array — Create a new array without copying the objects inside it.
- Remove duplicate values — Keep the first occurrence of each value, in its original order.
- Flatten a nested array — Turn a nested array into one sequence of values.