This article will show you how to create an array in JavaScript. There are several approaches to create an array in JavaScript, each with a description and complete code example are given below:
1. Array Literal
Using the array literal notation to directly define an array.
const newArray = [1, 2, 3, 4, 5]; // Output: [ 1, 2, 3, 4, 5 ] console.log(newArray);
2. Array Constructor
Using the Array
constructor to create an array.
const newArray = new Array(1, 2, 3, 4, 5); // Output: [ 1, 2, 3, 4, 5 ] console.log(newArray);
3. Array.from() Method
Using the Array.from()
method to create an array from an iterable object.
const newArray = Array.from([1, 2, 3, 4, 5]); // Output: [ 1, 2, 3, 4, 5 ] console.log(newArray);
4. Using Array.push() Method
Creating an empty array and then using the push()
method to add elements.
const newArray = []; newArray.push(1, 2, 3, 4, 5); // Output: [ 1, 2, 3, 4, 5 ] console.log(newArray);
5. Using Spread Operator (…)
Using the spread operator to create a new array by spreading elements from an existing array.
const existingArray = [1, 2, 3, 4, 5]; const newArray = [...existingArray]; // Output: [ 1, 2, 3, 4, 5 ] console.log(newArray);
6. Array.from() with Mapping
Using Array.from()
with a mapping function to create an array.
const newArray = Array.from({ length: 5 }, (_, index) => index + 1); // Output: [ 1, 2, 3, 4, 5 ] console.log(newArray);
7. Array.map() Method
Using the Array.map()
method to create a new array by applying a function to each element.
const existingArray = [1, 2, 3, 4, 5]; const newArray = existingArray.map(item => item * 2); // Output: [ 2, 4, 6, 8, 10 ] console.log(newArray);
8. Using Array.concat() Method
Using the concat()
method to concatenate multiple arrays.
const newArray = [].concat(1, 2, 3, 4, 5); // Output: [ 2, 4, 6, 8, 10 ] console.log(newArray);
9. Using Array.of() Method
Using the Array.of()
method to create an array with the provided elements.
const newArray = Array.of(1, 2, 3, 4, 5); // Output: [ 1, 2, 3, 4, 5 ] console.log(newArray);
10. Using Array.slice() Method
Using the slice()
method to create a new array by extracting a portion of an existing array.
const existingArray = [1, 2, 3, 4, 5]; const newArray = existingArray.slice(0); // Output: [ 1, 2, 3, 4, 5 ] console.log(newArray);
11. Using Array.fill() Method
Using the fill()
method to create an array with a specified value at each index.
const size = 5; const newArray = new Array(size).fill(0); // Output: [ 0, 0, 0, 0, 0 ] console.log(newArray);
12. Using Array.keys() with Spread Operator
Using Array.keys()
with the spread operator to create an array from the keys of an iterable.
const size = 5; const newArray = [...Array(size).keys()]; // Output: [ 0, 1, 2, 3, 4 ] console.log(newArray);