Creating new array js
In JavaScript, you can create a new array in several ways:
-
Using the
[]
syntax:let myArray = [];
This creates an empty array with no elements.
-
Using the
Array()
constructor:let myArray = new Array();
This also creates an empty array with no elements.
-
Using the
Array()
constructor with arguments:let myArray = new Array(5); // creates an array with 5 empty slots
This creates an array with 5 empty slots, but no actual elements.
-
Using the
Array()
constructor with multiple arguments:let myArray = new Array(1, 2, 3, 4, 5); // creates an array with the specified elements
This creates an array with the specified elements:
[1, 2, 3, 4, 5]
. -
Using the spread operator (
...
) with an existing array:let myArray = [...existingArray]; // creates a new array with the same elements as existingArray
This creates a new array with the same elements as the existing array.
-
Using the
Array.from()
method:let myArray = Array.from({ length: 5 }, () => 0); // creates an array with 5 elements, all set to 0
This 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
This creates an array with 5 elements, all set to 0.
These are some of the ways you can create a new array in JavaScript. The choice of method depends on your specific use case and requirements.