Quickly removing values from an array

Posted on

Setting the length of an array in JavaScript removes all values beyond that length. Setting the length to zero removes all values from it.

// this array holds six values
const numbers = [4, 8, 15, 16, 23, 42]
 
// by setting the length to 4, any value past the fourth element is removed
numbers.length = 4
console.log(numbers)  // ⇒ [4, 8, 15, 16]
 
// setting the length to 0 leads to the entire array being emptied
numbers.length = 0
console.log(numbers)  // ⇒ []
// this array holds six values
const numbers = [4, 8, 15, 16, 23, 42]
 
// by setting the length to 4, any value past the fourth element is removed
numbers.length = 4
console.log(numbers)  // ⇒ [4, 8, 15, 16]
 
// setting the length to 0 leads to the entire array being emptied
numbers.length = 0
console.log(numbers)  // ⇒ []
Debug
none
Grid overlay