Lesson illustration

Array Manipulation Fundamentals

Hello! Let's dive into our next lesson on JavaScript fundamentals.

In our last session, we explored JavaScript objects, which are perfect for storing related but unordered pieces of information using named keys, like a user's profile.

Today, we'll tackle another essential data structure that addresses a different need: how to manage ordered lists of items. This lesson fulfills the learning outcome: Create and manipulate arrays including adding, removing, and accessing elements.

As a designer, you frequently work with lists: a feed of social media posts, a list of products in a shopping cart, or a sequence of steps in a tutorial. JavaScript arrays are the tool we use to represent and manage these ordered collections in code.

1. What is an Array?

While objects are like a filing cabinet where each drawer has a specific name (a key), arrays are more like a numbered stack of boxes. The order matters, and you access each box by its number, not its name.

An array is an ordered list of values. Each value is called an element, and you can access it using a numeric index.

Let's start by understanding the basic concepts of creating and accessing arrays.

{
  "type": "video",
  "title": "Arrays in Javascript | Arrays Tutorial for Beginners",
  "id": "545a684b-ed36-4b9b-93c6-b32664e327ff",
  "video_id": "0SyTDl4pb4w",
  "part_indices": [
    0
  ],
  "par_intro": "This video from Dave Gray provides a great introduction to arrays. We'll start with the first few minutes to get a solid grasp of what they are and how to interact with them.",
  "par_directions": "Please watch from the beginning until **04:18**. Focus on these key points:\n\n*   The syntax for creating an empty array: `[]`.\n*   How elements are accessed using a zero-based index (e.g., `myArray[0]`).\n*   The concept of the `length` property, which tells you how many elements are in the array."
}

Key Concepts from the Video

  • Creation: You create an array using square brackets [].
    // An array of strings representing UI component tags
    let tags = ["button", "form", "modal", "card"];
    
    // An array with mixed data types
    let mixedData = ["Jane Doe", 32, true]; 
    
  • Zero-Based Indexing: The first element is at index 0, the second at index 1, and so on. This is a fundamental concept in most programming languages.
  • Accessing Elements: You use bracket notation with the index to get an element.
    console.log(tags[0]); // Outputs: "button"
    console.log(tags[2]); // Outputs: "modal"
    
  • Modifying Elements: You can also use bracket notation to change an element at a specific index.
    tags[1] = "input-field";
    console.log(tags); // Outputs: ["button", "input-field", "modal", "card"]
    
  • Length: The .length property gives you the total number of elements.
    console.log(tags.length); // Outputs: 4
    

2. Adding and Removing Elements

In UI development, lists are rarely static. Users add items to a cart, remove notifications, or post new comments. JavaScript provides simple methods to add and remove elements from the beginning or end of an array.

These methods are called "mutating" because they change the original array directly.

{
  "type": "video",
  "title": "Arrays in Javascript | Arrays Tutorial for Beginners",
  "id": "545a684b-ed36-4b9b-93c6-b32664e327ff",
  "video_id": "0SyTDl4pb4w",
  "part_indices": [
    1,
    2
  ],
  "par_intro": "Let's continue with the same video to see the four most common methods for adding and removing elements.",
  "par_directions": "Watch from **04:18** to **09:34**. The video will cover four key methods:\n\n1.  `push()`: Add to the end.\n2.  `pop()`: Remove from the end.\n3.  `unshift()`: Add to the beginning.\n4.  `shift()`: Remove from the beginning."
}

Here's a summary of those methods, which are essential for your toolkit:

MethodActionExample
push()Adds one or more elements to the end of an array.tags.push("header");
pop()Removes the last element from an array and returns it.let removedTag = tags.pop();
unshift()Adds one or more elements to the beginning of an array.tags.unshift("icon");
shift()Removes the first element from an array and returns it.let removedTag = tags.shift();

Think about a list of notifications in a UI. New notifications might be added to the top (unshift), while a user dismissing the oldest one would remove it from the top (shift). Adding an item to a "to-do" list might happen at the end (push).

3. Manipulating the Middle: splice()

What if you need to remove an element from the middle of a list, or insert a new one at a specific position? The splice() method gives you this surgical control. It's one of the most powerful array methods.

The name splice can be thought of like "splicing" a rope or film—you can cut a piece out, and optionally insert a new piece in its place.

{
  "type": "video",
  "title": "Arrays in Javascript | Arrays Tutorial for Beginners",
  "id": "545a684b-ed36-4b9b-93c6-b32664e327ff",
  "video_id": "0SyTDl4pb4w",
  "part_indices": [
    3,
    4
  ],
  "par_intro": "The `splice()` method can seem complex at first, but it's incredibly useful. This next segment of the video breaks it down clearly.",
  "par_directions": "Watch from **09:34** to **13:24**. Pay close attention to the parameters of `splice()`:\n\n1.  `start`: The index where the change begins.\n2.  `deleteCount`: How many elements to remove.\n3.  `item1, item2, ...`: The new elements to add (optional)."
}

Using splice() in Practice

Let's solidify this with a fresh example. Imagine you're managing the steps in a checkout process.

let checkoutSteps = ["Shipping", "Payment", "Review"];
  • To remove an element:
    To remove "Payment", we start at index 1 and remove 1 element.

    // Start at index 1, remove 1 element
    checkoutSteps.splice(1, 1); 
    console.log(checkoutSteps); // Outputs: ["Shipping", "Review"]
    
  • To add an element (without removing any):
    Let's add "Login" before "Shipping". We start at index 0, remove 0 elements, and add "Login".

    let checkoutSteps = ["Shipping", "Payment", "Review"];
    // Start at index 0, remove 0 elements, add "Login"
    checkoutSteps.splice(0, 0, "Login");
    console.log(checkoutSteps); // Outputs: ["Login", "Shipping", "Payment", "Review"]
    
  • To replace an element:
    Let's replace "Payment" with "Gift Card". We start at index 1, remove 1 element, and add "Gift Card".

    let checkoutSteps = ["Shipping", "Payment", "Review"];
    // Start at index 1, remove 1 element, add "Gift Card"
    checkoutSteps.splice(1, 1, "Gift Card");
    console.log(checkoutSteps); // Outputs: ["Shipping", "Gift Card", "Review"]
    

As the video mentions, avoid using delete on array elements (e.g., delete checkoutSteps[1]). It leaves an undefined "hole" in the array, which can cause unexpected bugs. splice is the correct tool for removing elements cleanly.

4. Your Turn: Managing a Playlist

Let's apply what you've learned. Imagine you are building a simple music player and need to manage the queue of upcoming songs.

Your Task:

  1. Open your code editor and create a new HTML file with a <script> tag, just like in the previous lesson.

  2. Inside the <script> tag, perform the following steps. Use console.log() to check the playlist array after each step to see your changes.

    a. Create the initial playlist: Define an array named playlist with the following three song titles (strings): "Bohemian Rhapsody", "Stairway to Heaven", "Hotel California".

    b. Add a song to the end: A user adds a new song to their queue. Use push() to add "Like a Rolling Stone" to the end of the playlist.

    c. Add a high-priority song to the start: The user wants to hear a song next. Use unshift() to add "Imagine" to the beginning of the playlist.

    d. The current song finishes: The first song in the queue has finished playing. Use shift() to remove it from the playlist.

    e. Remove a song from the middle: The user decides to remove "Stairway to Heaven" from the queue. It's now at index 1. Use splice() to remove it.

    f. Access the next song: After all these changes, log the song that is now at the start of the playlist to the console.

Click here to see the solution
// a. Create the initial playlist
let playlist = ["Bohemian Rhapsody", "Stairway to Heaven", "Hotel California"];
console.log("Initial playlist:", playlist);

// b. Add a song to the end
playlist.push("Like a Rolling Stone");
console.log("After push:", playlist);

// c. Add a high-priority song to the start
playlist.unshift("Imagine");
console.log("After unshift:", playlist);

// d. The current song finishes
let playedSong = playlist.shift();
console.log("Played song:", playedSong);
console.log("After shift:", playlist);

// e. Remove a song from the middle
// "Stairway to Heaven" is now at index 1
playlist.splice(1, 1);
console.log("After splice:", playlist);

// f. Access the next song
console.log("Next song to play:", playlist[0]); // Should be "Bohemian Rhapsody"

Conclusion

Excellent work! You now have the fundamental skills to manage ordered data in JavaScript. This is a critical building block for creating dynamic user interfaces.

Key Takeaways:

  • Arrays are for storing ordered lists of data, accessed by a numeric, zero-based index.
  • You can create an array with literal syntax: let myArray = [value1, value2];.
  • Use push() and pop() to efficiently add/remove elements at the end of an array.
  • Use unshift() and shift() to add/remove elements at the beginning.
  • Use splice() for precise control to add, remove, or replace elements anywhere in the array.

In this lesson, we manipulated arrays by adding, removing, and accessing individual elements. But what if you wanted to display every item in your playlist on the screen? Or calculate the total price of all items in a shopping cart? To do that, you need a way to perform an action on every element in an array. That's exactly what we'll cover in our next lesson: using loops to iterate over data arrays.

Can't find a good explanation? Sign up and we'll make it for you