DEV Community

Hiral
Hiral

Posted on

JavaScript Arrays 101

Think of storing multiple values, how will you store it

let fruit1 = "Apple";
let fruit2 = "Banana";
let fruit3 = "Mango";
let fruit4 = "Orange";
let fruit5 = "Grapes";
Enter fullscreen mode Exit fullscreen mode

This works, but it quickly becomes messy and difficult to manage. So you can use array to store

let fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"];
Enter fullscreen mode Exit fullscreen mode

An array is a collection of values stored in a single variable in a specific order.
Now all fruits are stored inside one array called fruits.

How to create Array
Creating an array is simple. We use square brackets [ ].
let numbers = [10, 20, 30, 40];
let mixed = ["John", 25, true];

Accessing Array Elements (Using Index)

Each element in an array has a position number called an index.

Important rule:
Array indexing starts from 0, not 1.

let fruits = ["Apple", "Banana", "Mango"];

console.log(fruits[0]); // Apple
console.log(fruits[1]); // Banana
console.log(fruits[2]); // Mango
Enter fullscreen mode Exit fullscreen mode

Updating Elements in an Array

We can change values using the index.

let fruits = ["Apple", "Banana", "Mango"];

fruits[1] = "Orange";

console.log(fruits);
output :["Apple", "Orange", "Mango"]
Enter fullscreen mode Exit fullscreen mode

Array Length Property

The length property tells us how many elements are in the array.

let fruits = ["Apple", "Banana", "Mango", "Orange"];

console.log(fruits.length);

Enter fullscreen mode Exit fullscreen mode

Looping Through an Array

Loops allow us to process every element automatically.

Example using a for loop:

let fruits = ["Apple", "Banana", "Mango"];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)