HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

5) Arrays, Objects and Useful Tools Lesson

Indexing JavaScript Arrays

13 min to complete · By Ian Currie

Dive into the world of arrays where managing a collection of data becomes a breeze. In this guide, you’ll discover how to pinpoint and modify individual elements within an array, such as the musicians array shown here:

let musicians = [
  "Jimi Hendrix",
  "Johnny Cash",
  "Elvis Presley",
  "Dolly Parton",
];

You'll learn to navigate through arrays using index numbers, allowing you to access and alter any item. This exploration will the basics of referencing individual elements, assigning values to specific positions, adding new elements and removing elements.

Reference an Element by Its Index

Accessing elements within an array is a straightforward process in JavaScript. You simply refer to the array by its name and then use the index number of the desired element inside square brackets. This index number is an integer that starts with zero, which corresponds to the first element in the array, and increases by one for each subsequent element. Here's how you can access the elements of the musicians array:

let musicians = [
  "Jimi Hendrix",
  "Johnny Cash",
  "Elvis Presley",
  "Dolly Parton",
];

// Access the first musician
musicians[0]; // This will retrieve "Jimi Hendrix"

// Access the second musician
musicians[1]; // This will retrieve "Johnny Cash"

// And so on for the rest of the elements
musicians[2]; // This will retrieve "Elvis Presley"
musicians[3]; // This will retrieve "Dolly Parton"

With this indexing method, JavaScript provides a simple and efficient way to retrieve the value stored at any specific position within an array.

Indexing Starts at Zero!

Notice how the first element is element 0. Most languages don't start counting at one like humans do, they start counting at zero. This has been the subject of countless memes among coders, mostly poking fun at languages in which arrays start at 1. This one illustrates how attached a coder can become to the benefits of starting arrays at 0:

Cartoon: One person asks if a dog bites, the dog responds 'Array indexing starts at 1,' leaving the asker in tears.

How to Assign Values to Arrays

Arrays in JavaScript are like flexible storage boxes where you can not only put things in but also change them or take them out as needed. They're mutable, which means you can add more items to your array, or remove some you don't need anymore. You can keep updating arrays with new data, or clean them out completely, making them incredibly versatile in managing and organizing data in your programs.

Assign a Value to an Existing Element in an Array

Arrays in JavaScript offer the flexibility to update their contents on the fly. You can change any item within an array simply by assigning a new value to it. This is done by referring to the array's name followed by the index of the item you want to replace, enclosed in square brackets. For example, if you decide that "Jimmy Page" should be the first musician in your musicians array instead of "Jimi Hendrix," you can make that change like this:

musicians[0] = "Jimmy Page"; // Assigns "Jimmy Page" to the first position
console.log(musicians); // Now the array has "Jimmy Page" as the first element

The array will now reflect this change, with "Jimmy Page" appearing as the first element. This mutable nature of arrays allows you to modify their contents as needed, whether you're updating a single item or replacing the entire list with your favorites.

Assign a Value to a New Element

JavaScript arrays are not fixed in size; you can easily add new elements to them. If you reference an index that is beyond the current length of the array, JavaScript doesn't mind—it just updates the array to include the new element. For example, if you have an array musicians with four elements and you assign a value to the fifth position (index 4), you extend the array:

musicians[4] = "Taylor Swift"; // This adds "Taylor Swift" as the fifth element
console.log(musicians);

However, if you skip some indices, like adding an element at index 10, JavaScript will fill the gap with undefined values, which might not be what you intended:

musicians[10] = "Elton John"; // This adds "Elton John" at the eleventh position
console.log(musicians);

// OUTPUT
[
  "Jimmy Page",
  "Johnny Cash",
  "Elvis Presley",
  "Dolly Parton",
  "Taylor Swift",
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  "Elton John",
];

Now your array has several undefined spaces between the fifth and eleventh positions. While this demonstrates the flexibility of JavaScript arrays, it's also a reminder to be cautious of how you assign new elements to avoid unintended gaps.

Add and Remove Items from an Array

You'll cover more methods to add and remove items from an array in a later lesson on using methods like .pop() and .push(), but in this section you'll get a quick overview of two of the most common methods to add and remove items from an array.

Colorful illustration of a light bulb

Typically, programmers prefer to add and remove items from an array instead of changing individual elements because it reduces the likelihood of errors or unintended side effects. It's a simpler operation to deal with. By overwriting individual elements, you run the risk of overwriting information that's already there, or of creating undefined gaps.

To add items to the end of an array in JavaScript, you can use the .push() method. It appends the new element to the array. For example:

let fruits = ["apple", "banana"];
fruits.push("orange"); // Adds "orange" to the end of the array
// ["apple", "banana", "orange"]

Removing items is just as simple with the .pop() method, which removes the last element from an array and returns that element. This changes the length of the array as well:

console.log(fruits); // ["apple", "banana", "orange"]
fruits.pop(); // This will remove "orange" from the end of the fruits array
console.log(fruits); // ["apple", "banana"]

Using push and pop, you can manage the items in your array, adding new ones or taking them out from the end of the array efficiently.

You'll be covering other methods to add and remove items from arrays in an upcoming lesson.

Use Variables To Reference an Item in a JavaScript Array

You can also use variables to retrieve a specific index:

let musicians = [
  "Jimi Hendrix",
  "Johnny Cash",
  "Elvis Presley",
  "Dolly Parton",
];

let indexOfBestGuitarist = 0;

console.log(
  musicians[indexOfBestGuitarist] // "Jimi Hendrix"
);

Use Expressions To Get JavaScript Array Items

In JavaScript, you're not limited to just using a literal number or a variable inside the square brackets; you can also use any expression that resolves to an integer. This expression is evaluated, and its result is used as the index to access an item in the array:

console.log(musicians);
// ["Jimi Hendrix", "Johnny Cash", "Elvis Presley", "Dolly Parton"]
console.log(musicians[1 + 1]); // "Elvis Presley"

If your expression evaluates to an index that's outside the bounds of the array—meaning there's no item at that position—JavaScript will return undefined:

console.log(musicians[10]); // `undefined`

This showcases the dynamic nature of JavaScript arrays and how they handle non-existent indices without throwing an error, so, it requires careful use to avoid unexpected results. In many other languages, trying to access an index of an array that is out of its bounds will throw an error.

Summary: Accessing and Changing Elements in a JavaScript Array

  • Arrays in JavaScript allow for easy management of data collections, enabling modification and access of individual elements via index numbers.
  • Index numbers in arrays start at 0, allowing for intuitive referencing of each element within an array, such as accessing "Jimi Hendrix" in a musicians array with musicians[0].
  • Arrays are mutable, meaning their content can be changed; values can be reassigned or updated using their index.
  • New elements can be added to arrays even if the index doesn't currently exist, but doing so carelessly can lead to 'undefined' gaps.
  • JavaScript provides methods like .push() to add items and .pop() to remove items from the end of an array.
  • Dynamic references, including variables and expressions, can be used to access array elements, offering flexibility but requiring careful use to avoid unintended outcomes.