Which of the following is the correct way to write an array?

Understanding JavaScript Arrays and Their Syntax

In JavaScript, an array is a single variable that is used to store different elements. It's an object, which makes it possible for us to store multiple values in a single variable.

In the quiz question provided, we're asked to identify the correct way to write an array. Among the provided options, the correct one is let fruits = new Array("apple","peach","banana");. Let's break down this syntax:

  • let: This is a keyword used to declare a variable in JavaScript.

  • fruits: This is the variable name. In this case, it's an array that will hold different types of fruits.

  • new Array(): This is the Array constructor, which we use to create an array object in JavaScript. The elements of the array are enclosed within the parentheses.

  • "apple", "peach", "banana": These are the elements of the array. As you can observe, each element is separated by a comma.

So, if we would want to access these elements, we can use their index, which starts at 0. For instance, if you want to call 'apple', you'll use fruits[0].

Here's a practical example of how this array can be used:

let fruits = new Array("apple","peach","banana");

// A function that prints elements of the fruits array
function printFruits() {
  for(let i = 0; i < fruits.length; i++) {
    console.log(`Fruit at index ${i} is ${fruits[i]}`);


This will print:

Fruit at index 0 is apple
Fruit at index 1 is peach
Fruit at index 2 is banana

JavaScript also provides another simple and widely used syntax for declaring arrays, known as the array literal syntax. It looks like this:

let fruits = ["apple", "peach", "banana"];

Both of these methods are absolutely correct. The choice between the two often comes down to personal preference or context, though the array literal syntax is more popular because it's shorter and simpler.

Do you find this helpful?