How to create an array in JavaScript?

689
february 22, 2023, at 22:00

In JavaScript, you can create an array by enclosing a list of elements inside square brackets []. Here's an example:

In this example, we have created an array called myArray with three elements: "apple", "banana", and "orange".

You can also create an empty array and add elements to it later, like this:

This code creates an empty array called myArray, and then uses the push() method to add the elements "apple", "banana", and "orange" to the array, one by one.

Array literal syntax

You can create an array by enclosing a comma-separated list of values inside square brackets:

Array constructor

You can also create an array using the Array constructor and passing in a list of values as arguments:

Array.from()

You can also create an array from an array-like object, such as a NodeList, by using the Array.from() method:

Spread operator

You can also use the spread operator (...) to create an array from a set of values:

// Output: ['h', 'e', 'l', 'l', 'o']