Master JavaScript Programming From Scratch

Clear, interactive, and structured JavaScript lessons designed for absolute beginners.

Arrays

Learn how JavaScript Arrays store multiple values inside a single variable and how to access and work with individual elements.

JavaScript Array creation, indexing, push and length

JavaScript Array example showing elements, indexes, adding values, and array length.

Simple Explanation

An Array is used to store multiple values inside a single variable.

For example, instead of creating separate variables for different course names, we can store all the course names inside one Array.

Each value inside an Array has an index. JavaScript Array indexing starts from 0.

Basic Array Syntax

const courses = [
    "Java",
    ".NET",
    "Python",
    "JavaScript"
];

Important Parts of an Array

1 Array Name

The variable used to store the Array.

2 Array Elements

The actual values stored inside the Array.

3 Index

The position number of an element. The first element starts at index 0.

4 length

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

Array Index Diagram

Array Elements and Their Indexes
Index 0
Java
Index 1
.NET
Index 2
Python
Index 3
JavaScript

Example 1: Creating an Array

We can create an Array using square brackets [].

const courses = [
    "Java",
    ".NET",
    "Python",
    "JavaScript"
];

console.log(courses);
Output:
Java, .NET, Python, JavaScript

Example 2: Accessing Array Elements

We can access an Array element using its index. Remember that the first index is 0.

const courses = [
    "Java",
    ".NET",
    "Python",
    "JavaScript"
];

console.log(courses[0]);
console.log(courses[2]);
Output:
Java
Python

Example 3: Finding Array Length

The length property tells us the number of elements present in an Array.

const courses = [
    "Java",
    ".NET",
    "Python",
    "JavaScript"
];

console.log(courses.length);
Output:
4

Example 4: Updating an Array Element

We can change an existing Array element by assigning a new value to its index.

const courses = [
    "Java",
    ".NET",
    "Python"
];

courses[1] = "JavaScript";

console.log(courses);
Output:
Java, JavaScript, Python
Important Note:

JavaScript Arrays are zero-indexed.

This means the first element has index 0, the second element has index 1, and so on.

Summary

An Array is a collection of multiple values stored inside a single variable. JavaScript Arrays use zero-based indexing, which means the first element is at index 0. We can create Arrays, access their elements, find their length, and update existing values using their indexes. JavaScript also provides many built-in Array methods for performing more operations.