- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- 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.
Lab 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.jsfile 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
solutiondirectory 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,
personis 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
0for the first element. In JavaScript, you can define an array using square brackets[]:const fruits = ['apple', 'banana', 'orange'];This example defines an array called
fruitsthat contains three string elements.To add an element to the end of an array, you can use the
pushmethod. Thepushmethod 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
numberscontaining three elements. It uses thepushmethod to add the number4to the end of the array.You can also add an object to an array using the
pushmethod.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 objectbook1with propertiestitleandauthor, and then it uses thepushmethod to addbook1to thebooksarray.Now that you understand objects, arrays, and how to add elements to an array, you're ready to implement the
addSongfunction. In thescript.jsfile, locate theaddSongfunction. 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
splicemethod. This method allows you to add or remove elements at a specific position in the array.The
splicemethod 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
fruitsarray contains four elements. It uses thesplicemethod to remove two elements starting from index1. After thespliceoperation, thefruitsarray only containsappleandgrape.You can also use the
splicemethod 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 and1as the second argument to thesplicemethod: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 index1from thestudentsarray.Now that you understand how to remove elements from an array using the
splicemethod, you're ready to implement theremoveSongfunction. In thescript.jsfile, locate theremoveSongfunction. This function takes the index of the song to be removed from theplaylistarray. ### 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
fruitsthat 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: 40In this example, there's an array
numbersand a variableindexwith 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
getSongDetailsfunction. In thescript.jsfile, locate thegetSongDetailsfunction. This function takes the index of the song from theplaylistarray 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
personobject with propertiesnameandage. It modifies theageproperty by assigning a new value of26using the dot notation. It also adds a new propertycityto thepersonobject 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 index1by assigning a new value ofgrapeusing 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 index1usingstudents[1]and then modifies theageproperty 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
modifySongfunction. In thescript.jsfile, locate themodifySongfunction. 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
forEachLoops are used to iterate over elements in an array or perform repetitive tasks. One commonly used loop construct is the
forEachloop, which provides a convenient way to iterate over each element in an array.The
forEachloop 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 thatforEachis being applied to.
Here's the general syntax of the
forEachloop: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 aforEachloop to iterate over each element in the array. The callback function takes thenumberparameter, 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 5You 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
forEachloop: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
studentsarray containing objects representing student information. It uses theforEachloop to iterate over each student object. Inside the callback function, it accesses thenameandageproperties 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: 21Using the
forEachloop 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
forEachloop to iterate over array elements, you can apply this knowledge to complete the implementation of thedisplaySongsfunction. In thescript.jsfile, locate thedisplaySongsfunction in thePresentation Logic Section. This function should display the songs in theplaylistarray 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
trueorfalse. The most common conditional statements in JavaScript areif,else if, andelse.1.
ifstatement: Theifstatement 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
conditionevaluates totrue, the code inside the curly braces{}will be executed. If theconditionisfalse, 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
agevariable is greater than or equal to18, the messageYou are considered an adult in most countries.will be logged to the console.2.
elsestatement: Theelsestatement is used in conjunction with anifstatement to execute a block of code when theifcondition 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
conditionin theifstatement istrue, the code block inside theifwill be executed. If theconditionisfalse, the code block inside theelsewill 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
agevariable is less than18, the condition in theifstatement isfalse, so the code block inside theelsewill be executed, and the messageYou are not eligible to vote yet.will be logged to the console.3.
else ifstatement: Theelse ifstatement is used to specify additional conditions to check if the previousifcondition 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 theifwill be executed. Ifcondition1isfalse, the program will move on to evaluatecondition2. Ifcondition2istrue, the code block inside theelse ifwill be executed. If bothcondition1andcondition2arefalse, the code block inside theelsewill 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
gradevariable is85, the first conditiongrade >= 90isfalse, so the program moves on to theelse ifcondition. The conditiongrade >= 80istrue, 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
displayPlaylistandhandleFormSubmitfunctions. In thescript.jsfile, locate thedisplayPlaylistfunction. This function should display the playlist on the web page based on whether theplaylistarray is empty or contains songs. In thescript.jsfile, locate thehandleFormSubmitfunction in thePresentation Logic Section. This function handles the submission of the form and determines whether a song should be added or modified. ### Error Handling withthrowandErrorIn JavaScript, you can use the
throwstatement 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
Errorobject constructor to represent the error. TheErrorobject 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
catchblock to handle the error. If nocatchblock is found, the program terminates, and the error message is typically displayed in the console.You can use the
throwstatement in combination with control flow statements likeifandelseto 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
dividefunction checks if the second argumentbis equal to zero. If it is, an error is thrown with the messageDivision by zero is not allowed.using thethrowstatement and theErrorobject 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
modifySongfunction. In thescript.jsfile, locate themodifySongfunction. 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!
-
About the author
Real skill practice before real-world application
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.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.