Constructor for creating new arrays
In JavaScript, there are several ways to create a new array. Here are a few common methods:
- The
[]
syntax: This is the most common way to create a new array. Simply use the square brackets[]
and you'll get a new, empty array.const myArray = [];
- The
Array()
constructor: You can use theArray()
constructor to create a new array. Pass in the desired length of the array as an argument.const myArray = new Array(5); // creates an array of length 5
- The
Array.from()
method: This method creates a new array from an iterable object, such as an array-like object or a string.const myArray = Array.from('hello'); // creates an array ['h', 'e', 'l', 'l', 'o']
- The
...
spread operator: You can use the spread operator to create a new array from an existing array or iterable object.const myArray = [...'hello']; // creates an array ['h', 'e', 'l', 'l', 'o']
- The
Array.prototype.concat()
method: This method creates a new array by concatenating one or more arrays.const myArray = [1, 2, 3].concat([4, 5, 6]); // creates an array [1, 2, 3, 4, 5, 6]
Note that when using the
Array()
constructor, you can also pass in an argument to specify the initial values of the array. For example:const myArray = new Array(5, 10, 15); // creates an array [5, 10, 15]