An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
January 4, 2022 08:37 pm GMT
Original Link: https://dev.to/marcostl/5-ways-of-creating-an-array-in-javascript-hk9
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];
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');
Original Link: https://dev.to/marcostl/5-ways-of-creating-an-array-in-javascript-hk9
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To