Create new array javascript
Here are a few ways to create a new array in JavaScript:
Method 1: Using the []
syntax
let myArray = [];
This creates an empty array with no elements.
Method 2: Using the Array()
constructor
let myArray = new Array();
This also creates an empty array with no elements.
Method 3: 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.
Method 4: Using the Array()
constructor with elements
let myArray = new Array("apple", "banana", "orange"); // creates an array with 3 elements
This creates an array with 3 elements: "apple", "banana", and "orange".
Method 5: Using the spread operator (...
)
let myArray = [...]; // creates an empty array
This creates an empty array.
Method 6: Using the Array.from()
method
let myArray = Array.from({ length: 5 }); // creates an array with 5 empty slots
This creates an array with 5 empty slots.
Note that in JavaScript, arrays are objects, so you can also create an array by assigning an object to a variable and then using the Array.prototype
methods to manipulate it. For example:
let myArray = {};
myArray.push("apple");
myArray.push("banana");
console.log(myArray); // Output: ["apple", "banana"]
This creates an object with a push
method, which is a part of the Array.prototype
object.