An Idiosyncratic Blog

⛓ Revisiting Arrays in JavaScript

Published on
3 minutes read

Creation

To create new array which, you cannot iterate over, you can use array constructor:

const arr = Array(10) // => Array(10) [ <10 empty slots> ]
// OR
const arr = new Array(10) // => Array(10) [ <10 empty slots> ]

If you try to use .map() you'll get undefined.

To create arrays, which can be iterated over we can:

  • Array.apply: Array.apply(null, Array(10))
  • Destructuring operator: [...Array(10)]
  • Array.from Array.from({ length: 10 })
const arr = Array.apply(null, Array(10))
// OR
const arr = [...Array(10)]
// OR
const arr = Array.from({ length: 4 })

// => Array(10) [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined ]
  • Array.prototype.fill Array(10).fill('Hello!')
Array(10).fill('Hello!')

// => Array(10) [ "Hello!", "Hello!", "Hello!", "Hello!", "Hello!", "Hello!", "Hello!", "Hello!", "Hello!", "Hello!" ]

Filling in

We can use the map method to fill in values after initialising the array:

Array.apply(null, Array(4)).map((u, i) => i) // => [0, 1, 2, 3]

[...Array(5)].map((u, i) => i) [0, 1, 2, 3] // => [0, 1, 2, 3, 4]

Array.from({ length: 4 }).map((u, i) => i) // => [0, 1, 2, 3]

Array(5).fill(null).map((u, i) => i + 1 ) // => [1, 2, 3, 4, 5]

Emptying out

Usually when we want to empty an array, we can simply re-initialize to []. This creates a new array and assigns a reference to it to a variable. Any other references are unaffected and still points to the original array.

let arr = Array.from({ length: 4 }).map((u, i) => i) // => [0, 1, 2, 3]
let arr2 = arr
arr = []
console.log(arr) // => []
console.log(arr2) // => [0, 1, 2, 3]

Another way to empty an array is to assign its length property to 0. This modifies the array itself. If you access it via a different variable, then you still get the modified array.

let arr = Array.from({ length: 4 }).map((u, i) => i) // => [0, 1, 2, 3]
let arr2 = arr
arr.length = 0
console.log(arr) // => []
console.log(arr2) // => []

And that's it!

Do you know more ways to create and manipulate arrays? Let me know in the comments below