JavaScriptLoops, Arrays & Strings

Javascript 1D Array

Learn how to use 1D arrays in JavaScript to store and manage lists of data effectively.

What is a 1D Array?Link to this section

A 1D array is a special variable that can hold a list of multiple values under a single name. Instead of creating separate variables for every item, an array keeps them together in a specific order.

This creates an array of three fruit names and prints the first item.

  • `let fruits` declares the array variable
  • `["apple", "banana", "cherry"]` is the array literal holding three items
  • `[0]` is the index used to access the first item in the list
  • `console.log()` prints the result to the console

A 1D array is used whenever you need to store ordered lists of data such as user names, test scores, or shopping items.

Why Do We Need 1D Arrays?Link to this section

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

  • Store a list of student marks in a gradebook
  • Keep track of items in a shopping cart bill
  • Save a sequence of high scores in a game
  • List registered email addresses for a login system
  • Record daily temperature values for a weather app
  • Manage a queue of customer names at a support desk

We store multiple exam scores in one array and add them together.

Instead of making four variables like mark1, mark2, mark3, and mark4, we group them in one array for easier management.

About 1D ArraysLink to this section

Arrays use numbered positions called indices to locate items, starting at zero. JavaScript arrays are dynamic, meaning they can grow or shrink as needed, and they can hold mixed data types though keeping them uniform is best.

ConceptDescriptionExample
IndexPosition of an element, starts at 00
LengthTotal number of items in the arrayarray.length
ElementThe actual value stored at an index"apple"

You can change individual items inside an array using their index number.

Essential Operations and Methods for 1D ArraysLink to this section

1. Accessing and Modifying ElementsLink to this section

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

Reading and updating an element using its index.

Modifying a price value directly using arithmetic.

warning

Attempting to access an index that does not exist will return undefined instead of throwing an error.

tip

Always remember that JavaScript array indices start at 0, so the last item is at length minus one.

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

You can add new items to an array using built-in methods. push adds to the end, while unshift adds to the beginning.

push adds an item to the end of the array.

unshift adds an item to the beginning of the array.

note

Both push and unshift methods return the new total length of the array after adding the item.

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

You can remove items from an array as well. pop removes from the end, while shift removes from the beginning.

pop removes and returns the last element.

shift must be called on the array instance like tasks.shift().

tip

Use pop and shift when implementing queue or stack data structures in your application.

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

You can search for specific values inside an array to check if they exist or find where they are located.

indexOf returns the index, and includes returns a boolean.

warning

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

5. Looping Through ArraysLink to this section

Arrays are most powerful when combined with loops to process every item one by one.

Using a standard for loop to print each score.

tip

Always use array.length as the condition limit in your loops so it adapts if items are added or removed.

Array Length PropertyLink to this section

The length property keeps track of how many items are in an array and can even be used to truncate or clear an array.

Manually shortening the length property cuts off extra elements.

note

Setting an array's length to 0 is a quick way to clear all items from the array.

Complete Coding ExampleLink to this section

A complete program calculating the total sum of prices in a shopping cart.

This example loops through a 1D array of prices, adds each price to a running total, and prints the final cart amount.

Important NotesLink to this section

  • Arrays store multiple values in a single variable under an ordered list.
  • Array indices always start at 0.
  • The last element of an array is at index array.length minus one.
  • Use push() to add items to the end of an array.
  • Use pop() to remove the last item from an array.
  • Use unshift() to add items to the start of an array.
  • Use shift() to remove the first item from an array.
  • The length property tells you how many items are in the array.
  • indexOf() returns the position of an item or -1 if missing.
  • includes() returns true if an item exists in the array.
  • Arrays can hold mixed data types, but keeping them uniform is a best practice.

SummaryLink to this section

In this lesson, you learned how to create and manage 1D arrays in JavaScript. You discovered how to access elements using indices, add and remove items with built-in methods, and loop through lists to perform calculations. Arrays are a fundamental building block for storing collections of data in web applications.

Check Your UnderstandingLink to this section

Javascript 1D Array quiz
Question 1 of 6

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

Practice ChallengesLink to this section

1. Print Favorite Fruits

easy

Create a 1D array with three of your favorite fruits. Use console.log to print the second fruit in the array.

Expected output

banana

Hint: Remember that index counting starts at 0.

2. Add to Shopping List

easy

Create an array with two grocery items. Use push() to add a third item, then print the entire array.

Expected output

[ 'milk', 'bread', 'eggs' ]

Hint: Call push() on your array variable before logging it.

3. Calculate Exam Average

medium

Create an array of four test scores: 80, 90, 85, 95. Write code to sum them up and divide by the array length to find the average, then print the average.

Expected output

87.5

Hint: Add all elements together and divide by array.length.

4. Remove First and Last

medium

Create an array of numbers [10, 20, 30, 40]. Use pop() to remove the last item and shift() to remove the first item. Print the remaining array.

Expected output

[ 20, 30 ]

Hint: Apply shift() and pop() on the array variable.

5. Find Maximum Score

hard

Given an array of scores [45, 88, 92, 67, 34], write a loop to find and print the highest score in the array.

Expected output

92

Hint: Assume the first item is the max, then loop through and update if a higher number is found.

Rate this content

Sign in to rate

Discussion

Sign in to join the discussion