Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 48

Array Basics: Creation and Indexing

This lesson is built with resources from youtube.com, javascript.info and 1 more site.

Hello! Welcome to a new module in your JavaScript journey.

In our last module, we dove deep into JavaScript objects, learning how to create them, add properties and methods, and even use modern ES6 syntax to make them more concise. Objects are fantastic for storing unordered, related data, like the properties of a user.

Today, we begin a new module focusing on another cornerstone of programming: Arrays. While objects are like dictionaries, arrays are like ordered lists. They are essential for managing collections of data, from a simple to-do list to a complex set of posts fetched from a database in a Next.js application.

This lesson will focus on the very first, and most important, operations with arrays. Our goal is to learn how to create arrays and access/modify elements by index. By the end of this lesson, you'll be able to create your own lists of data and confidently retrieve or change any item within them.

What is an Array?

Imagine you want to keep a list of your favorite movies. With what you know so far, you might do this:

const movie1 = 'Inception';
const movie2 = 'The Matrix';
const movie3 = 'Interstellar';

This works, but it's clumsy. What if you had 100 movies? You'd need 100 variables! This is where arrays come in. An array is a single special variable that can hold an ordered list of multiple values.

For a great introduction to this idea, please read the first section of the following article from the Mozilla Developer Network (MDN).

Arrays - Learn web development | MDN

The article 'Arrays' on MDN provides a clear definition of what arrays are and why they are so useful for managing lists of data.

Read the section titled 'What is an array?'. It will give you a solid foundation for why we need this data structure.


Creating Your First Array

Creating an array in JavaScript is straightforward. You use square brackets [], and separate the items (called "elements") with commas.

// An empty array
const emptyList = [];

// An array of strings
const movies = ['Inception', 'The Matrix', 'Interstellar'];

// An array of numbers
const primeNumbers = [2, 3, 5, 7, 11];

// Arrays can also hold a mix of different data types
const mixedBag = ['Hello', 100, true, null];

The video below offers a great visual demonstration of creating arrays.

JavaScript Arrays Crash Course

The video 'JavaScript Arrays Crash Course' by Web Dev Simplified provides a very clear and direct explanation of how to create an array.

Watch the segment from 00:27 to 01:51. Pay close attention to the square bracket syntax and how elements are separated by commas.


Accessing Elements by Index

Once you have an array, how do you get the items back out? Arrays are ordered, and each element has a numbered position called an index.

Here is the most important rule to remember about arrays in JavaScript (and most other programming languages): Indexing starts at 0.

  • The first element is at index 0.
  • The second element is at index 1.
  • The third element is at index 2.
  • ...and so on.

This is a fundamental concept, and because you like to understand the "why," it's rooted in how computers calculate memory addresses. Thinking of the index as an "offset" from the start of the array can be helpful. The first item is at an offset of 0 from the start.

To access an element, you use the array's name followed by the index in square brackets: arrayName[index].

Let's look at our movies array again:

const movies = ['Inception', 'The Matrix', 'Interstellar'];

console.log(movies[0]); // Output: 'Inception'
console.log(movies[1]); // Output: 'The Matrix'
console.log(movies[2]); // Output: 'Interstellar'

The following image provides a perfect visual breakdown of this concept.

Introduction to JavaScript Arrays: Elements and Indices
This diagram shows an array with four elements. Notice how the indices run from 0 to 3, while the total number of items, its 'length', is 4.

What if you use an index that doesn't exist?

If you try to access an index that is outside the bounds of the array, JavaScript won't give you an error. Instead, it will return the value undefined.

const movies = ['Inception', 'The Matrix', 'Interstellar'];
console.log(movies[3]); // Output: undefined

The following video segment reinforces the concept of zero-based indexing and shows what happens when you access an element that doesn't exist.

JavaScript Arrays Crash Course

Let's continue with the 'JavaScript Arrays Crash Course' video to see indexing in action.

Watch from 01:51 to 02:58. This part clearly explains how the zero-based numbering system works for accessing elements.

Finding the Array's Length

Every array has a built-in length property that tells you how many elements it contains.

const movies = ['Inception', 'The Matrix', 'Interstellar'];
console.log(movies.length); // Output: 3

const emptyList = [];
console.log(emptyList.length); // Output: 0

Because indexing starts at 0, the index of the last element is always length - 1. This is a very common pattern!

const movies = ['Inception', 'The Matrix', 'Interstellar'];
// movies.length is 3, so the last index is 3 - 1 = 2
const lastMovie = movies[movies.length - 1]; 
console.log(lastMovie); // Output: 'Interstellar'
Test your understanding!

Consider the following array:
const playlist = ['Bohemian Rhapsody', 'Stairway to Heaven', 'Hotel California', 'Like a Rolling Stone'];

  1. What code would you write to log the song "Stairway to Heaven" to the console?
  2. What is the value of playlist.length?
  3. What code would you write to log the last song in the playlist to the console, using the .length property?
Show answer
  1. console.log(playlist[1]); (Remember, indexing starts at 0!)
  2. The value is 4.
  3. console.log(playlist[playlist.length - 1]);

Modifying Array Elements

Arrays in JavaScript are "mutable," which is a fancy way of saying you can change them after they are created. You can change an element by accessing it via its index and assigning a new value, just like with a variable.

const schedule = ['Wake up', 'Eat', 'Code', 'Sleep'];

// Let's change the third item
schedule[2] = 'Learn JavaScript';

// Now the array is changed
console.log(schedule); // Output: ['Wake up', 'Eat', 'Learn JavaScript', 'Sleep']

You can even use this syntax to add a new element at a specific index.

const fruits = ['Apple', 'Orange'];
console.log(fruits.length); // Output: 2

// Add a new element at index 2
fruits[2] = 'Pear';

console.log(fruits);        // Output: ['Apple', 'Orange', 'Pear']
console.log(fruits.length); // Output: 3

To solidify your understanding of accessing and modifying arrays, please read the following material.

Arrays

The javascript.info website offers another excellent, concise explanation with interactive examples.

In the article, focus on the code examples under the main 'Declaration' heading. Specifically, review the parts that show getting an element (fruits[0]), replacing an element (fruits[2] = 'Pear'), and adding a new one (fruits[3] = 'Lemon').

Test your understanding!

You are building a settings panel for an application. The settings are stored in an array.

let settings = ['Dark Mode', 'Notifications On', 'English'];

Write the code to perform the following two steps in order:

  1. Change 'Dark Mode' to 'Light Mode'.
  2. Log the entire updated settings array to the console.
Show answer
let settings = ['Dark Mode', 'Notifications On', 'English'];

// 1. Change 'Dark Mode' to 'Light Mode'. 'Dark Mode' is at index 0.
settings[0] = 'Light Mode';

// 2. Log the entire updated array.
console.log(settings); 
// Expected output: ['Light Mode', 'Notifications On', 'English']

Conclusion

Great work! You've just learned the absolute fundamentals of one of the most important data structures in programming. This knowledge is the foundation for everything we'll do with lists of data from here on out.

Key Takeaways:

  • Arrays are ordered lists of values, created with square brackets [].
  • Elements in an array are accessed by their index, which is a number starting from 0.
  • The syntax for accessing an element is myArray[index].
  • Arrays have a .length property that tells you the total number of elements. The last element's index is always length - 1.
  • You can change an element's value by assigning a new value to its index: myArray[index] = newValue.

Next Up

Now that you know how to create an array and access or change its elements by their position, what's next? In our next lesson, we will explore built-in array "methods" that allow you to easily add and remove elements from the beginning or end of an array, using push, pop, shift, and unshift.