DEV Community

marcostl
marcostl

Posted on • Originally published at marcostl.co

5 ways of creating an Array in JavaScript

1. Explicitly

Using the square bracket notation. This is probably the most common way of creating an Array.

const arr = [1, 2, 3];
Enter fullscreen mode Exit fullscreen mode

2. Destructuring another array

Using the ES6 notation you can create a copy of another array. Specially useful in functional programming to avoid side effects (i.e. modifying the original array).

const numbers = [1, 2, 3, 4];

const copyOfNumbers = [...numbers];

// You can also join 2 arrays into one:
const numbersTwice = [...numbers, ...numbers];
// This will be [ 1, 2, 3, 4, 1, 2, 3, 4 ]
Enter fullscreen mode Exit fullscreen mode

3. Array's constructor

JavaScript defines an Array constructor that allows you to specify the length of the array. This method is useful if you know how large your array is going to be. Note that the constructor will create an array where all the elements are empty (not undefined).

const emptyArray = new Array(5);

console.log(emptyArray);
// [ <5 empty items> ]

console.log(emptyArray.length);
// 5
Enter fullscreen mode Exit fullscreen mode

4. Array.from()

This method accepts an iterator (which can be another array or a set) and creates a new array with the same elements.

const copiedArray = Array.from([1, 2, 3]);
Enter fullscreen mode Exit fullscreen mode

5. Array.of()

This method accepts an unlimited number of parameters that will be used as elements of the new constructed array.

const paramsArray = Array.of('a', 'b', 'c');
Enter fullscreen mode Exit fullscreen mode

Latest comments (4)

Collapse
 
valeriavg profile image
Valeria

Array.from is much more than that!
Check this out:

Array.from('abc')
// ['a','b','c']
Enter fullscreen mode Exit fullscreen mode

Oh and it also takes an optional second parameter:

Array.from([1, 2, 3], x => x + x);
// [2,4,6]
Enter fullscreen mode Exit fullscreen mode

developer.mozilla.org/en-US/docs/W...

Collapse
 
marcostl profile image
marcostl

Yes! Any iterator would do!

I wasn't aware of the optional 2nd parameter, that's really nice!

Collapse
 
posandu profile image
Posandu

Javascript power

Collapse
 
bmarotta profile image
bmarotta

You can copy the array also with slice():

const copyOfNumbers = numbers.slice();
Enter fullscreen mode Exit fullscreen mode