Explain array creation in JavaScript with example

There are two ways to create an array in JavaScript:

  • Using an array literal
  • Using the Array constructor

Using an array literal

An array literal is a comma-separated list of values enclosed in square brackets. For example:

Code snippet

const myArray = [1, 2, 3];

This creates an array with three elements: 1, 2, and 3.

Using the Array constructor

The Array constructor is a function that creates an array. The syntax is as follows:

Code snippet

const myArray = new Array();

This creates an empty array. You can then add elements to the array using the push() method. For example:

Code snippet

const myArray = new Array();
myArray.push(1);
myArray.push(2);
myArray.push(3);

This creates an array with three elements: 1, 2, and 3.

I hope this helps! Let me know if you have any other questions.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top