0

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?

4

3 Answers 3

1

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))
Sign up to request clarification or add additional context in comments.

Comments

0

@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' ].

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.