Javascript Arrays

An array in JavaScript is a special type of object used to store multiple values in a single variable. Instead of creating separate variables for each value, you can store all related values in one array and access them using their index positions.

Arrays are commonly used to store lists of names, numbers, products, student marks, and other collections of data.

What Is an Array in JavaScript?

An array is a collection of values stored in a single variable. Each value in an array is called an element. Every element has an index that identifies its position in the array.

For example, suppose you want to store three programming languages. You could create separate variables:

let language1 = "JavaScript";
let language2 = "Python";
let language3 = "Java";

However, managing many variables this way can become difficult. Instead, you can use an array:

let languages = ["JavaScript", "Python", "Java"];

console.log(languages);

Output:

["JavaScript", "Python", "Java"]

Now, all three programming languages are stored in a single variable called languages.

How to Create an Array in JavaScript

You can create an array in JavaScript using square brackets []. Place the values inside the brackets and separate each value with a comma.

Syntax:

let arrayName = [value1, value2, value3];

Here is a simple example:

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

console.log(fruits);

Output:

["Apple", "Banana", "Mango"]

In this example:

  • fruits is the array variable.
  • [] represents the array.
  • "Apple", "Banana", and "Mango" are the array elements.
  • Commas separate the elements.

You can also create an empty array and add values later.

let colors = [];

colors[0] = "Red";
colors[1] = "Green";
colors[2] = "Blue";

console.log(colors);

Output:

["Red", "Green", "Blue"]

JavaScript Array Index

An array uses index numbers to identify the positions of its elements. In JavaScript, array indexing starts at 0, not 1.

Consider this array:

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

Its index positions are:

ElementIndex
Apple0
Banana1
Mango2

The first element has index 0, the second has index 1, and the third has index 2.

You can access an element by writing its index inside square brackets.

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

console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);

Output:

Apple
Banana
Mango

If you try to access an index that does not contain an element, JavaScript generally returns undefined.

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

console.log(fruits[5]);

Output:

undefined

How to Find the Length of an Array

The length property returns the number of elements in an array.

Syntax:

arrayName.length;

Example:

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

console.log(fruits.length);

Output:

4

The array contains four elements, so its length is 4.

Remember that the length is not the same as the last index. For a non-empty, dense array, the last index is usually one less than the length.

For example, an array with four elements has indexes 0 through 3, but its length is 4.

Different Types of Values in an Array

JavaScript arrays can contain different types of values, including strings, numbers, booleans, and even other arrays or objects.

Array of Strings

An array of strings stores text values.

let languages = ["JavaScript", "Python", "Java"];

console.log(languages[0]);

Output:

JavaScript

Array of Numbers

An array of numbers stores numeric values.

let marks = [85, 90, 78, 92];

console.log(marks[1]);

Output:

90

Array of Booleans

An array can also store Boolean values: true and false.

let answers = [true, false, true];

console.log(answers[1]);

Output:

false

Array with Different Data Types

JavaScript does not require every element in an array to have the same data type.

let student = ["Karim", 22, true];

console.log(student);

Output:

["Karim", 22, true]

This array contains a string, a number, and a Boolean value. Although this is allowed, using clear and consistent data structures can make larger applications easier to maintain.

How to Change an Array Element

You can update an existing array element by assigning a new value to its index.

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

fruits[1] = "Orange";

console.log(fruits);

Output:

["Apple", "Orange", "Mango"]

The element at index 1 changes from "Banana" to "Orange". The other elements remain unchanged.

How to Add Elements to an Array

JavaScript provides several ways to add elements to an array.

Using the push() Method

The push() method adds one or more elements to the end of an array.

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

fruits.push("Mango");

console.log(fruits);

Output:

["Apple", "Banana", "Mango"]

Using the unshift() Method

The unshift() method adds one or more elements to the beginning of an array.

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

fruits.unshift("Apple");

console.log(fruits);

Output:

["Apple", "Banana", "Mango"]

How to Remove Elements from an Array

You can remove elements using methods such as pop() and shift().

Using the pop() Method

The pop() method removes the last element from an array and returns the removed value.

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

let removedFruit = fruits.pop();

console.log(fruits);
console.log(removedFruit);

Output:

["Apple", "Banana"]
Mango

Using the shift() Method

The shift() method removes the first element from an array and returns it.

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

let removedFruit = fruits.shift();

console.log(fruits);
console.log(removedFruit);

Output:

["Banana", "Mango"]
Apple

Both pop() and shift() modify the original array.

How to Loop Through an Array

A loop allows you to access or process each element in an array. For example, you can use a for loop to display every element.

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

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

Output:

Apple
Banana
Mango

The loop starts at index 0 and continues while i is less than the array’s length. During each iteration, it prints the element at the current index.

You can also use a for...of loop when you need the values directly.

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

for (let fruit of fruits) {
    console.log(fruit);
}

Output:

Apple
Banana
Mango

The for...of loop assigns each array element to the variable fruit.

Array vs. Variable

A regular variable usually stores one value at a time, while an array can store multiple values in a single collection.

FeatureRegular variableArray
PurposeStores an individual valueStores a collection of values
Examplelet age = 22;let ages = [20, 22, 25];
AccessUsing the variable nameUsing an index
Multiple valuesRequires separate variables or another structureCan hold multiple elements
Common useStoring one person’s ageStoring ages of multiple people

Where Are JavaScript Arrays Used?

Arrays are useful in many real-world applications.

  • Student management systems: Store student names, marks, or IDs.
  • E-commerce websites: Store product lists, shopping cart items, and categories.
  • Web applications: Display menus, notifications, and search results.
  • Data analysis: Process collections of numbers or records.
  • Games: Store player scores, inventory items, or game levels.

Arrays make it easier to organize, access, update, and process collections of related data.

Frequently Asked Questions

What is an array in JavaScript?

An array is a special object that stores multiple values in a single variable. Each element can be accessed using its index.

How do you declare an array in JavaScript?

You can declare an array using square brackets:

let colors = ["Red", "Green", "Blue"];

Does JavaScript array indexing start at 0 or 1?

JavaScript array indexing starts at 0. The first element is at index 0, and the second element is at index 1.

How do you find the number of elements in an array?

Use the length property:

let numbers = [10, 20, 30];

console.log(numbers.length);

Output: 3.

Can a JavaScript array contain different data types?

Yes. A JavaScript array can contain strings, numbers, booleans, objects, other arrays, and other values.

What is the difference between push() and pop()?

The push() method adds elements to the end of an array, while pop() removes and returns the last element.

Are JavaScript arrays mutable?

Yes. JavaScript arrays are mutable, which means their elements can be changed and methods such as push(), pop(), shift(), and unshift() can modify the original array.