- Lab
- Core Tech

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.

Path Info
Table of Contents
-
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:
-
index.html
: The HTML file that defines the structure and layout of the application. -
styles.css
: The CSS file that contains the styles for the visual appearance of the application. -
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. -
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
, andprofession
.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. Thepush
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 thepush
method to add the number4
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 objectbook1
with propertiestitle
andauthor
, and then it uses thepush
method to addbook1
to thebooks
array.Now that you understand objects, arrays, and how to add elements to an array, you're ready to implement the
addSong
function. In thescript.js
file, locate theaddSong
function. This function takes the song and artist names and adds them to the playlist array as an object. ### Removing Elements from an ArrayYou 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:- The index at which to start changing the array (required).
- The number of elements to remove (optional).
- 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 thesplice
method to remove two elements starting from index1
. After thesplice
operation, thefruits
array only containsapple
andgrape
.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 and1
as the second argument to thesplice
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 index1
from thestudents
array.Now that you understand how to remove elements from an array using the
splice
method, you're ready to implement theremoveSong
function. In thescript.js
file, locate theremoveSong
function. This function takes the index of the song to be removed from theplaylist
array. ### Accessing Array ElementsArrays 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 of0
, the second element has an index of1
, 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 usesfruits[0]
, which returnsapple
. Similarly,fruits[1]
returnsbanana
, andfruits[2]
returnsorange
.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 variableindex
with a value of2
. When it usesnumbers[index]
, it retrieves the element at index2
, which is30
. You can also use expressions likenumbers[index + 1]
to access the element at index3
(2 + 1
), which is40
.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 thescript.js
file, locate thegetSongDetails
function. This function takes the index of the song from theplaylist
array as a parameter. ### Modifying Object Properties and Array ElementsTo 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 propertiesname
andage
. It modifies theage
property by assigning a new value of26
using the dot notation. It also adds a new propertycity
to theperson
object and assign it the valueNew 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 index1
by assigning a new value ofgrape
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 index1
usingstudents[1]
and then modifies theage
property of that object by assigning a new value of23
.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 thescript.js
file, locate themodifySong
function. This function takes the index of the song to be modified, the new song name, and the new artist name as parameters. -
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:currentValue
: The current element being processed in the array.index
(optional): The index of the current element being processed.array
(optional): The array thatforEach
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 aforEach
loop to iterate over each element in the array. The callback function takes thenumber
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 theforEach
loop to iterate over each student object. Inside the callback function, it accesses thename
andage
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 thedisplaySongs
function. In thescript.js
file, locate thedisplaySongs
function in thePresentation Logic Section
. This function should display the songs in theplaylist
array on the web page. -
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
orfalse
. The most common conditional statements in JavaScript areif
,else if
, andelse
.1.
if
statement: Theif
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 totrue
, the code inside the curly braces{}
will be executed. If thecondition
isfalse
, 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 to18
, the messageYou are considered an adult in most countries.
will be logged to the console.2.
else
statement: Theelse
statement is used in conjunction with anif
statement to execute a block of code when theif
condition isfalse
. 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 theif
statement istrue
, the code block inside theif
will be executed. If thecondition
isfalse
, the code block inside theelse
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 than18
, the condition in theif
statement isfalse
, so the code block inside theelse
will be executed, and the messageYou are not eligible to vote yet.
will be logged to the console.3.
else if
statement: Theelse if
statement is used to specify additional conditions to check if the previousif
condition isfalse
. 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'strue
, the code block inside theif
will be executed. Ifcondition1
isfalse
, the program will move on to evaluatecondition2
. Ifcondition2
istrue
, the code block inside theelse if
will be executed. If bothcondition1
andcondition2
arefalse
, the code block inside theelse
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 is85
, the first conditiongrade >= 90
isfalse
, so the program moves on to theelse if
condition. The conditiongrade >= 80
istrue
, so the messageYou 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
andhandleFormSubmit
functions. In thescript.js
file, locate thedisplayPlaylist
function. This function should display the playlist on the web page based on whether theplaylist
array is empty or contains songs. In thescript.js
file, locate thehandleFormSubmit
function in thePresentation Logic Section
. This function handles the submission of the form and determines whether a song should be added or modified. ### Error Handling withthrow
andError
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. TheError
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 nocatch
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 likeif
andelse
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 argumentb
is equal to zero. If it is, an error is thrown with the messageDivision by zero is not allowed.
using thethrow
statement and theError
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 thescript.js
file, locate themodifySong
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. -
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:
-
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.
-
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.
-
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.
-
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.
-
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!
-
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.