JavaScriptLoops, Arrays & Strings

Introduction to Arrays

Learn how to store multiple values in a single variable using JavaScript arrays with this beginner-friendly tutorial.

What is a JavaScript Array?Link to this section

A JavaScript array is a special variable that can hold more than one value at a time under a single name. Instead of creating separate variables for each item, an array organizes a list of items sequentially using numbered indexes.

This example creates an array of fruits and prints the first item.

  • `let fruits` is the **variable declaration**.
  • `[` and `]` are the **array brackets** that enclose the items.
  • "apple", "banana", "cherry" are the **array elements** separated by commas.
  • `[0]` is the **index** used to access the first item.

Arrays are used whenever you need to store collections of data, such as a list of student names, shopping cart items, or high scores.

Why Do We Need Arrays?Link to this section

Without arrays, managing multiple related values becomes tedious and requires dozens of separate variables.

  • Store a list of student exam marks in a single grade book.
  • Keep track of items added to an online shopping cart.
  • Save a sequence of user login timestamps.
  • Manage a playlist of favorite songs.
  • Store coordinates for a map application.
  • List winning lottery numbers for a draw.

Using an array allows us to check the total number of marks instantly using the length property.

Instead of creating four separate variables like mark1, mark2, mark3, and mark4, we group them into one array and easily check their total count.

About JavaScript ArraysLink to this section

Arrays are objects in JavaScript that are specifically designed for storing ordered collections of data. They use zero-based indexing, meaning the first item is always at index 0. Arrays can hold mixed data types, though it is best practice to keep elements of the same type together.

ConceptDescriptionExample
IndexThe numerical position of an element0, 1, 2
LengthThe total count of items in the arrayarray.length
Zero-basedIndexing starts at 0 instead of 1First item is index 0

An array can hold strings, numbers, and booleans all at once.

Types of Array Operations and MethodsLink to this section

1. Accessing and Modifying Array ElementsLink to this section

You can access or change any element in an array by referencing its index number inside square brackets.

Replacing green with yellow using index 1.

tip

Always remember that array indexes start at 0. The last item is always at length minus one.

2. Adding Elements with push() and unshift()Link to this section

To add new items to an array, use built-in methods. push() adds items to the end, while unshift() adds them to the beginning.

Charlie is added to the end of the queue.

note

Both push and unshift return the new length of the array after adding the elements.

3. Removing Elements with pop() and shift()Link to this section

To remove items from an array, use pop() to remove the last element and shift() to remove the first element.

Task 3 is removed from the end.

warning

Calling pop or shift on an empty array will not throw an error; it will simply return undefined.

4. Finding Elements with indexOf() and includes()Link to this section

You can check if an item exists in an array or find its exact position using indexOf and includes.

Includes returns true if the element is found.

tip

indexOf returns -1 if the element is not found in the array.

5. Looping Through ArraysLink to this section

You can use loops like 'for' or array methods like 'forEach' to go through every item in an array one by one.

Doubles each number in the array.

note

Combining arrays with loops is the foundation of processing lists of data in JavaScript.

Array Mutability and ConstLink to this section

Declaring an array with const means the variable identifier cannot be reassigned, but the contents of the array can still be modified freely.

Even though scores is constant, we can modify its contents.

warning

Reassigning a const array entirely (e.g., scores = [40, 50]) will cause a TypeError.

Complete Coding ExampleLink to this section

This complete example manages a shopping cart by adding items at both ends and printing the final list.

This script demonstrates creating an array, modifying it with push and unshift, and looping through all items to print them.

Important NotesLink to this section

  • Arrays store multiple values in a single variable under one name.
  • Array indexes always start at zero.
  • The length property gives the total number of items in an array.
  • push() adds an element to the end of an array.
  • pop() removes the last element from an array.
  • unshift() adds an element to the beginning of an array.
  • shift() removes the first element from an array.
  • includes() checks if a specific value exists in an array.
  • Arrays declared with const can still have their contents modified.
  • You can store mixed data types in a single array.

SummaryLink to this section

In this lesson, you learned how JavaScript arrays allow you to store and manage lists of data efficiently. You explored how to access items by index, add and remove elements using built-in methods, and loop through arrays. Mastering arrays is an essential step toward handling complex data structures in your applications.

Check Your UnderstandingLink to this section

Introduction to JavaScript Arrays quiz
Question 1 of 7

What is the index of the first item in a JavaScript array?

Practice ChallengesLink to this section

1. Create a Fruit List

easy

Create an array with three of your favorite fruits. Print the second fruit in the array to the console.

Expected output

banana

Hint: Remember that indexes start at 0.

2. Add to Playlist

easy

Create an array with two song titles. Use push() to add a third song to the end, then print the new length of the array.

Expected output

3

Hint: Call push() on your array, then log array.length.

3. Remove First Guest

medium

Create an array of three guest names. Remove the first guest using the correct array method, and print the updated array length.

Expected output

2

Hint: Use the shift() method to remove the first item.

4. Check Inventory

medium

Given an array of store items ['pen', 'pencil', 'eraser'], check if 'notebook' is in the array using includes() and print the result.

Expected output

false

Hint: Use array.includes('notebook').

5. Sum of Marks

hard

Create an array of four student marks. Use a loop to calculate the sum of all marks and print the total.

Expected output

350

Hint: Initialize a sum variable at 0 and add each element inside a for loop.

Rate this content

Sign in to rate

Discussion

Sign in to join the discussion