Arrays
Learn how JavaScript Arrays store multiple values inside a single variable and how to access and work with individual elements.
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
The variable used to store the Array.
The actual values stored inside the Array.
The position number of an element. The first element starts at index 0.
The length property tells us how many elements are present in the Array.
Array Index Diagram
Example 1: Creating an Array
We can create an Array using square brackets [].
const courses = [
"Java",
".NET",
"Python",
"JavaScript"
];
console.log(courses);
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]);
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);
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);
Java, JavaScript, Python
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.