Create a new array in javascript
There are several ways to create a new array in JavaScript:
-
Using the
[]
syntax:let myArray = [];
This creates an empty array.
-
Using the
Array()
constructor:let myArray = new Array();
This also creates an empty array.
-
Using the
Array()
constructor with arguments:let myArray = new Array(5); // creates an array with 5 elements, all set to undefined
-
Using the
Array()
constructor with arguments and initial values:let myArray = new Array(5, 10, 15); // creates an array with 3 elements: 5, 10, and 15
-
Using the spread operator (
...
) with an existing array:let myArray = [...existingArray]; // creates a new array with the same elements as existingArray
-
Using the
Array.from()
method:let myArray = Array.from({ length: 5 }, () => 0); // creates an array with 5 elements, all set to 0
-
Using the
Array.prototype.fill()
method:let myArray = new Array(5).fill(0); // creates an array with 5 elements, all set to 0
Note that the
[]
syntax is the most common and concise way to create a new array in JavaScript.