Create a new array in javascript

There are several ways to create a new array in JavaScript:

  1. Using the [] syntax:

    let myArray = [];

    This creates an empty array.

  2. Using the Array() constructor:

    let myArray = new Array();

    This also creates an empty array.

  3. Using the Array() constructor with arguments:

    let myArray = new Array(5); // creates an array with 5 elements, all set to undefined
  4. 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
  5. Using the spread operator (...) with an existing array:

    let myArray = [...existingArray]; // creates a new array with the same elements as existingArray
  6. Using the Array.from() method:

    let myArray = Array.from({ length: 5 }, () => 0); // creates an array with 5 elements, all set to 0
  7. 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.