1. Explicitly
Using the square bracket notation. This is probably the most common way of creating an Array.
const arr = [1, 2, 3];
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 ]
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
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]);
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');
Top comments (4)
Array.from
is much more than that!Check this out:
Oh and it also takes an optional second parameter:
developer.mozilla.org/en-US/docs/W...
Javascript power
Yes! Any iterator would do!
I wasn't aware of the optional 2nd parameter, that's really nice!
You can copy the array also with slice():