Featured resource
pluralsight tech forecast
2025 Tech Forecast

Which technologies will dominate in 2025? And what skills do you need to keep up?

Check it out
Hamburger Icon
  • Labs icon Lab
  • Core Tech
Labs

Guided: Mastering Control Flow and Collections with JavaScript

This Guided Code Lab will teach you how to master essential JavaScript concepts such as control flow, loops, and collections by building an interactive Music Playlist Manager application. You'll gain hands-on experience in implementing conditional statements, iterating over arrays, manipulating arrays, and working with objects inside arrays.

Labs

Path Info

Level
Clock icon Beginner
Duration
Clock icon 1h 8m
Published
Clock icon May 23, 2024

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Table of Contents

  1. Challenge

    Introduction

    Welcome to the lab Guided: Mastering Control Flow and Collections with JavaScript.

    In this lab, you'll use control flow and collections to create a Music Playlist Manager application in JavaScript with the following features:

    • Display the current playlist of songs.
    • Allow users to add new songs to the playlist by specifying the song name and artist name.
    • Enable users to modify existing songs in the playlist.
    • Provide the ability to remove songs from the playlist.

    The application allows users to view the current playlist, which displays the songs along with their corresponding artist names. To add a new song, users will fill out a form by entering the song name and artist name. Upon form submission, the song will be added to the playlist. Users can also modify existing songs by clicking the Modify button next to a song, which will populate the form with the song's current details. After making changes and submitting the form, the song will be updated in the playlist. Additionally, users can remove songs from the playlist by clicking the Remove button next to each song. ### Familiarizing with the Program Structure

    The application is built with HTML, CSS, and JavaScript. It includes the following files:

    1. index.html: The HTML file that defines the structure and layout of the application.

    2. styles.css: The CSS file that contains the styles for the visual appearance of the application.

    3. script.js: The JavaScript file that contains the necessary functions and logic for application functionality.

    The script.js file is partially completed, containing the necessary business and presentation logic function declarations. You'll focus on implementing the functions related to the business logic.

    You can switch to the Web Browser tab to review the application. To load your latest changes, click on the Refresh button located at the top-left corner of the tab. Initially, you won't be able to add new songs. However, you can explore the application and familiarize with the user interface.

    Start by examining the provided code and understanding the program structure. When you're ready, dive into the coding process. If you encounter any problems, remember that a solution directory is available for reference or to verify your code.

  2. Challenge

    Collections

    Introduction to Objects and Arrays

    An object is a data structure that allows you to store related data and functionality together. Objects consist of properties (also known as attributes) and methods. Properties are variables that hold values, while methods are functions that perform actions related to the object.

    You can create an object using object literal notation, which involves defining the object and its properties inside curly braces {}:

    let person = {
      name: 'Jane',
      age: 25,
      profession: 'Developer'
    };
    

    In this example, person is an object with three properties: name, age, and profession.

    Objects can be stored in collections. A collection is a data structure that allows you to store and organize multiple elements. One of the most commonly used collections is an array.

    An array is an ordered collection of elements, where each element can be accessed using its index. The index represents the position of an element in the array, starting from 0 for the first element. In JavaScript, you can define an array using square brackets []:

    const fruits = ['apple', 'banana', 'orange'];
    

    This example defines an array called fruits that contains three string elements.

    To add an element to the end of an array, you can use the push method. The push method takes one or more elements as arguments and adds them to the end of the array.

    Example:

    const numbers = [1, 2, 3];
    numbers.push(4);
    console.log(numbers); // Output: [1, 2, 3, 4]
    

    This example starts with an array numbers containing three elements. It uses the push method to add the number 4 to the end of the array.

    You can also add an object to an array using the push method.

    For example:

    const books = [];
    const book1 = {
      title: 'Book 1',
      author: 'Author 1'
    };
    books.push(book1);
    console.log(books); // Output: [{ title: 'Book 1', author: 'Author 1' }]
    

    This example starts with an empty array books. It defines an object book1 with properties title and author, and then it uses the push method to add book1 to the books array.

    Now that you understand objects, arrays, and how to add elements to an array, you're ready to implement the addSong function. In the script.js file, locate the addSong function. This function takes the song and artist names and adds them to the playlist array as an object. ### Removing Elements from an Array

    You can remove elements from an array using the splice method. This method allows you to add or remove elements at a specific position in the array.

    The splice method takes three parameters:

    1. The index at which to start changing the array (required).
    2. The number of elements to remove (optional).
    3. The elements to add to the array (optional).

    Here's an example:

    const fruits = ['apple', 'banana', 'orange', 'grape'];
    fruits.splice(1, 2);
    console.log(fruits); // Output: ['apple', 'grape']
    

    In this example, a fruits array contains four elements. It uses the splice method to remove two elements starting from index 1. After the splice operation, the fruits array only contains apple and grape.

    You can also use the splice method to remove objects from an array. If you want to remove a single element at a specific index, you can pass the index as the first argument and 1 as the second argument to the splice method:

    const students = [
      { name: 'John', age: 20 },
      { name: 'Jane', age: 22 },
      { name: 'Mark', age: 21 }
    ];
    students.splice(1, 1);
    console.log(students); // Output: [{ name: 'John', age: 20 }, { name: 'Mark', age: 21 }]
    

    In this example, there's an array, students, containing objects representing student information. splice(1, 1) removes the object at index 1 from the students array.

    Now that you understand how to remove elements from an array using the splice method, you're ready to implement the removeSong function. In the script.js file, locate the removeSong function. This function takes the index of the song to be removed from the playlist array. ### Accessing Array Elements

    Arrays are used to store multiple values in a single variable. Each value in an array is called an element, and each element has a specific position or index. Array indexes start at 0, meaning the first element has an index of 0, the second element has an index of 1, and so on.

    To access an element in an array, you can use the square bracket notation along with the index of the element you want to retrieve:

    const fruits = ['apple', 'banana', 'orange'];
    console.log(fruits[0]); // Output: 'apple'
    console.log(fruits[1]); // Output: 'banana'
    console.log(fruits[2]); // Output: 'orange'
    

    In this example, there's an array called fruits that contains three elements. To access the first element, it uses fruits[0], which returns apple. Similarly, fruits[1] returns banana, and fruits[2] returns orange.

    You can also use variables or expressions inside the square brackets to dynamically access elements based on the value of the variable or the result of the expression:

    const numbers = [10, 20, 30, 40, 50];
    const index = 2;
    console.log(numbers[index]); // Output: 30
    console.log(numbers[index + 1]); // Output: 40
    

    In this example, there's an array numbers and a variable index with a value of 2. When it uses numbers[index], it retrieves the element at index 2, which is 30. You can also use expressions like numbers[index + 1] to access the element at index 3 (2 + 1), which is 40.

    Now that you understand how to access elements in an array using indexes, you're ready to apply this knowledge in the getSongDetails function. In the script.js file, locate the getSongDetails function. This function takes the index of the song from the playlist array as a parameter. ### Modifying Object Properties and Array Elements

    To modify the properties of an object, you can use the dot notation (object.property) or the square bracket notation (object['property']). You can assign a new value to an existing property or add a new property to the object:

    const person = {
      name: 'John',
      age: 25
    };
    
    // Modifying an existing property
    person.age = 26;
    
    // Adding a new property
    person.city = 'New York';
    
    console.log(person); // Output: { name: 'John', age: 26, city: 'New York' }
    

    In this example, there's a person object with properties name and age. It modifies the age property by assigning a new value of 26 using the dot notation. It also adds a new property city to the person object and assign it the value New York.

    To access and modify elements in an array, you can use the square bracket notation with the index of the element you want to access or modify:

    const fruits = ['apple', 'banana', 'orange'];
    
    // Modifying an element
    fruits[1] = 'grape';
    
    console.log(fruits); // Output: ['apple', 'grape', 'orange']
    

    In this example, there's an array, fruits, with three elements. It modifies the element at index 1 by assigning a new value of grape using the square bracket notation.

    When you have an array of objects, you can access individual objects using the array index and then modify the properties of that object:

    const students = [
      { name: 'John', age: 20 },
      { name: 'Jane', age: 22 },
      { name: 'Mark', age: 21 }
    ];
    
    // Modifying an object property within an array
    students[1].age = 23;
    
    console.log(students[1]); // Output: { name: 'Jane', age: 23 }
    

    In this example, there's an array, students, containing objects representing student information. It accesses the object at index 1 using students[1] and then modifies the age property of that object by assigning a new value of 23.

    Now that you understand how to modify object properties and access and modify array elements, you're ready to apply this knowledge in the modifySong function. In the script.js file, locate the modifySong function. This function takes the index of the song to be modified, the new song name, and the new artist name as parameters.

  3. Challenge

    Loops

    Looping Through Arrays Using forEach

    Loops are used to iterate over elements in an array or perform repetitive tasks. One commonly used loop construct is the forEach loop, which provides a convenient way to iterate over each element in an array.

    The forEach loop is a method available on arrays that takes a callback function as an argument. The callback function is executed for each element in the array, and it receives three parameters:

    1. currentValue: The current element being processed in the array.
    2. index (optional): The index of the current element being processed.
    3. array (optional): The array that forEach is being applied to.

    Here's the general syntax of the forEach loop:

    array.forEach(function(currentValue, index, array) {
      // Code to be executed for each element
    });
    

    This is an example:

    const numbers = [1, 2, 3, 4, 5];
    
    numbers.forEach(function(number) {
      console.log(number);
    });
    

    This example has an array, numbers, containing five elements. It uses a forEach loop to iterate over each element in the array. The callback function takes the number parameter, which represents the current element being processed. Inside the callback function, it logs each number to the console.

    This is the output:

    1
    2
    3
    4
    5
    

    You can also use an arrow function as the callback function for a more concise syntax:

    numbers.forEach(number => {
      console.log(number);
    });
    

    When working with arrays of objects, you can access the properties of each object inside the forEach loop:

    const students = [
      { name: 'John', age: 20 },
      { name: 'Jane', age: 22 },
      { name: 'Mark', age: 21 }
    ];
    
    students.forEach(student => {
      console.log(`Name: ${student.name}, Age: ${student.age}`);
    });
    

    In this example, there's a students array containing objects representing student information. It uses the forEach loop to iterate over each student object. Inside the callback function, it accesses the name and age properties of each student object and logs them to the console.

    This is the output:

    Name: John, Age: 20
    Name: Jane, Age: 22
    Name: Mark, Age: 21
    

    Using the forEach loop is a convenient and readable way to iterate over elements in an array and perform actions on each element.

    Now that you understand how to use the forEach loop to iterate over array elements, you can apply this knowledge to complete the implementation of the displaySongs function. In the script.js file, locate the displaySongs function in the Presentation Logic Section. This function should display the songs in the playlist array on the web page.

  4. Challenge

    Conditional Statements

    Conditional Statements and Program Flow Control

    In programming, conditional statements are used to make decisions and control the flow of a program based on certain conditions. They allow you to execute different blocks of code depending on whether a specific condition is true or false. The most common conditional statements in JavaScript are if, else if, and else.

    1. if statement: The if statement is used to execute a block of code if a specified condition is true. Here's the general syntax:

    if (condition) {
      // Code to be executed if the condition is true
    }
    

    If the condition evaluates to true, the code inside the curly braces {} will be executed. If the condition is false, the code block will be skipped, and the program will move on to the next statement. For example:

    const age = 18;
    
    if (age >= 18) {
      console.log("You are considered an adult in most countries.");
    }
    

    In the above example, if the age variable is greater than or equal to 18, the message You are considered an adult in most countries. will be logged to the console.

    2. else statement: The else statement is used in conjunction with an if statement to execute a block of code when the if condition is false. Here's the general syntax:

    if (condition) {
      // Code to be executed if the condition is true
    } else {
      // Code to be executed if the condition is false
    }
    

    If the condition in the if statement is true, the code block inside the if will be executed. If the condition is false, the code block inside the else will be executed. For example:

    const age = 16;
    
    if (age >= 18) {
      console.log("You are considered an adult.");
    } else {
      console.log("You are considered a minor.");
    }
    

    In the above example, since the age variable is less than 18, the condition in the if statement is false, so the code block inside the else will be executed, and the message You are not eligible to vote yet. will be logged to the console.

    3. else if statement: The else if statement is used to specify additional conditions to check if the previous if condition is false. It allows you to chain multiple conditions together. Here's the general syntax:

    if (condition1) {
      // Code to be executed if condition1 is true
    } else if (condition2) {
      // Code to be executed if condition1 is false and condition2 is true
    } else {
      // Code to be executed if both condition1 and condition2 are false
    }
    

    The program will first evaluate condition1. If it's true, the code block inside the if will be executed. If condition1 is false, the program will move on to evaluate condition2. If condition2 is true, the code block inside the else if will be executed. If both condition1 and condition2 are false, the code block inside the else will be executed. For example:

    const grade = 85;
    
    if (grade >= 90) {
      console.log("You got an A!");
    } else if (grade >= 80) {
      console.log("You got a B.");
    } else {
      console.log("You got a grade below B.");
    }
    

    In the above example, since the grade variable is 85, the first condition grade >= 90 is false, so the program moves on to the else if condition. The condition grade >= 80 is true, so the message You got a B. will be logged to the console.

    Conditional statements allow you to create branching paths in your program based on different conditions. They enable you to make decisions and execute specific blocks of code depending on the values of variables or the results of expressions.

    Now that you understand conditional statements and program flow control, you can apply this knowledge to implement the displayPlaylist and handleFormSubmit functions. In the script.js file, locate the displayPlaylist function. This function should display the playlist on the web page based on whether the playlist array is empty or contains songs. In the script.js file, locate the handleFormSubmit function in the Presentation Logic Section. This function handles the submission of the form and determines whether a song should be added or modified. ### Error Handling with throw and Error

    In JavaScript, you can use the throw statement to throw an error when an exceptional condition occurs in your code. This allows you to handle errors gracefully and provide meaningful feedback to the user or developer.

    When you throw an error, you can create an instance of the Error object constructor to represent the error. The Error object takes an optional error message as a parameter, which can be used to provide details about the error.

    Here's the general syntax for throwing an error:

    throw new Error('Error message');
    

    When an error is thrown, the normal flow of the program is interrupted, and the JavaScript runtime looks for the nearest catch block to handle the error. If no catch block is found, the program terminates, and the error message is typically displayed in the console.

    You can use the throw statement in combination with control flow statements like if and else to handle specific error conditions. For example:

    function divide(a, b) {
      if (b === 0) {
        throw new Error('Division by zero is not allowed.');
      }
      return a / b;
    }
    

    In this example, the divide function checks if the second argument b is equal to zero. If it is, an error is thrown with the message Division by zero is not allowed. using the throw statement and the Error object constructor. This prevents the function from attempting an invalid division and provides a clear error message.

    Now that you understand how errors and program flow control are related, you can apply this knowledge to improve the modifySong function. In the script.js file, locate the modifySong function. This function modifies a song in the playlist at a specific index with the provided song name and artist name. However, it currently does not handle the case where an invalid index is passed.

  5. Challenge

    Conclusion

    Congratulations on successfully completing this Code Lab!

    To try the application, navigate to the Web Browser tab. Then, click the Refresh button located in the top-left corner to load your changes. You can also click the Open in new browser tab icon in the top-right corner to open the application in a new browser tab. As a test, you can add a few songs, then try to modify one and delete another. ### Extending the Program

    Consider exploring these ideas to further enhance your skills and expand the capabilities of the program:

    1. Multiple Playlists: Allow users to create multiple playlists and switch between them. This can be achieved by modifying the data structure to store multiple playlists, adding UI elements for creating and selecting playlists, and updating the existing functions to handle multiple playlists.

    2. Persistent Storage: Persist playlists across page refreshes using local storage. When the page loads, check if there are any saved playlists in local storage and load them. Whenever a playlist is modified (songs added, removed, or modified), update the local storage to ensure the changes are preserved.

    3. Search Functionality: Implement a search functionality that allows users to search for songs by name or artist. Add a search input field and a search button to the UI. When the user enters a search query, filter the playlist based on the song name or artist name and display the matching results.

    4. Sorting Options: Add a feature to sort the playlist alphabetically by song name or artist name. Include UI elements, such as buttons or dropdown menus, to allow users to select the sorting criteria. Implement the sorting logic to rearrange the songs in the playlist based on the selected criteria.

    5. Favorite Songs: Introduce a feature that allows users to mark songs as favorites. Add a Favorite button or icon next to each song in the playlist. When a user clicks on the favorite button, toggle the favorite status of the song. Display the favorite songs prominently or provide an option to filter the playlist to show only the favorite songs. ### Related Courses on Pluralsight's Library If you're interested in further honing your JavaScript skills or exploring more topics, Pluralsight offers several excellent courses in the following path:

    These courses cover many aspects of JavaScript programming. Check them out to continue your learning journey in JavaScript!

Esteban Herrera has more than twelve years of experience in the software development industry. Having worked in many roles and projects, he has found his passion in programming with Java and JavaScript. Nowadays, he spends all his time learning new things, writing articles, teaching programming, and enjoying his kids.

What's a lab?

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Provided environment for hands-on practice

We will provide the credentials and environment necessary for you to practice right within your browser.

Guided walkthrough

Follow along with the author’s guided walkthrough and build something new in your provided environment!

Did you know?

On average, you retain 75% more of your learning if you get time for practice.