KaBe
KaBe

Reputation: 11

JS create array with arrow function and rest parameters

In one app I saw this part of code:

const arrayCreate = length => [...Array(length)];

It works, but I'm not sure how. We have a arrow function that takes a length parameter, and creates an array in array or what? :) And what does the spread operator doing here?

Upvotes: 0

Views: 1864

Answers (3)

Maxime Helen
Maxime Helen

Reputation: 1412

Interesting! The developer who made this probably wanted to optimize the performance at writing a first value at index or to be able to iterate through the empty values

An array is a javascript object that have:

  • key/value pairs assigned to respectively array's index/ value at index
  • length (size of the array)
  • prototype (getters, setters, array methods...)

Array(length) or new Array(length) returns { length: 0, prototype: {} }. The object is empty, with the length equals to passed in length

Now [...Array(length)] will return { 0: undefined, 1: undefined, 2: undefined: 3: undefined, 4: undefined, 5: undefined, length: 5, prototype: {} }. The properties are now allocated to their undefined values

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196187

Array(length) will create an array of length empty slots, for which, though, you cannot map or iterate using array methods like .map .forEach etc.

When you spread (...) the array with the empty slots it will create a new array with undefined for each array position. So you can now .map and .forEach because they are not empty slots.

So this is a way to create an array of length filled with undefined.

You could do the same with

Array(length).fill()

or

Array.from(Array(length))

Upvotes: 1

Kartik Chauhan
Kartik Chauhan

Reputation: 3068

@Gabrielse's post answers the question pretty well. However, there's just one more thing that I'd like to add to it.

One use-case where you might do something like this is when you have a set iterable and you want its elements inside an array. for e.g.

const set = new Set();
set.add('foo');
set.add('bar');
set.add('baz');

Suppose, you've the items foo, bar, baz in a set. A simple console.log(set); would result Set { 'foo', 'bar', 'baz' }. The result you get of course is a set. But what if you want these items in an array?

A simple way to do this would be to use ...(spread operator) applied to the set inside an array. The result of console.log([...set]); would be [ 'foo', 'bar', 'baz' ].

Upvotes: 0

Related Questions