Array in JavaScript

Aditya PandeyAditya Pandey
2 min read

What is Array?

An array is a data structure that allows to store and organize multiple values of different types in a single variable. You can think of it as a list or a collection of related items.
The array is defined by enclosing a comma-separated list of values within square brackets. following code snippet:

Example:

Let fruits = [“apple”, “banana”, “orange”, “Mango”];
Console.log(fruits) // you get array in result

Arrays in JavaScript are zero-indexed, which means that the first element in the array is at index 0, the second element is at index 1, and so on. You can access individual elements in the array using their index, like this:

Example:

Let fruits = [“apple”, “banana”, “orange”, “mango”];
Console.log(fruits[0])   // result is apple
Console.log(fruits[1])   // result is banana 
Console.log(fruits[2])   // result is orange

You can also change the value of an element in the array by assigning a new value to the corresponding index, like this:

fruits[1] = Strawberry,;
console.log(fruits); // outputs [apple, strawberry, orange, mango]

We can also write an array using string and number and boolean values:

Example:

Let fruits = [“apple”, “banana”, “orange”, “Mango” 1, 2, 3, false];
Console.log(fruits)

There are different ways to create an array in JavaScript. Let's explore some methods to create an array.

  1. Using array literals:
let myArray = [1, 2, 3, 4];
  1. Using the Array() constructor:
Using the Array() constructor:
  1. Using the Array() constructor with a single argument that specifies the length of the array:
let myArray = new Array(4);
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
myArray[3] = 4;
  1. Using the Array. of the () method to create an array with the specified elements:
let myArray = Array.of(1, 2, 3, 4);

These are some of the ways you can create arrays in JavaScript.

Thank You

0
Subscribe to my newsletter

Read articles from Aditya Pandey directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aditya Pandey
Aditya Pandey