In this lab, you will practice creating and manipulating arrays in JavaScript. You’ll start by creating basic arrays, access elements, and then explore how to iterate over arrays using different types of loops. Finally, you’ll work with array methods and practice with an array of objects.
In arrays.js, complete each drill by writing the JavaScript code for the following tasks. Be sure to test your functions by invoking them and checking the console to ensure they work as expected.
-
Create an array named
colorswith five colors of your choice. -
Access and print the first and last elements of the
colorsarray. -
Modify the second element of the
colorsarray to a new color.
-
Use a regular
forloop to print each element of thecolorsarray on a new line. -
Use a regular
forloop to print the elements of thecolorsarray in reverse order. -
Use a
whileloop to print each element of thecolorsarray. -
Use a
whileloop to print the elements of thecolorsarray in reverse order. -
Use a
for...ofloop to print each element of thecolorsarray.
- Loop through the nested array using a
forloop and create a sentence for each subarray.
Example sentence: "This past January I went skiing in Aspen."
-
Create an array of objects named
products. Each object should have aname,price, andinStockkey.
Example:{ name: 'Shirt', price: 19.99, inStock: true } -
Loop over the
productsarray and print out the name and price of each product. -
Use a conditional while iterating over the
productsarray. If the product is inStock, print out the sentence:
"The [product name] is available for [price]."
-
Use the
push()method to add a new color to thecolorsarray. -
Use the
pop()method to remove the last element from thecolorsarray. -
Use the
slice()method to extract a portion of thecolorsarray. -
Use the
splice()method to remove an element from the middle of thecolorsarray. -
Use the
join()method to convert thecolorsarray into a single string. -
Use the
indexOf()method to find the index of a specific color in thecolorsarray. -
Use the
includes()method to check if a specific color is in thecolorsarray. -
Use the
reverse()method to reverse the order of the elements in thecolorsarray.
-
Use the
sort()method to alphabetically sort thecolorsarray. -
Use the
filter()method to create a new array containing only colors with more than five letters. -
Use the
map()method to convert each color in thecolorsarray to uppercase.
- Complete all drills in the file arrays.js.
- Test each drill by running your code and checking the output in the console.
- Push your completed work to your repository and submit the link on Google Classroom.
- Be prepared to explain how your code works during a follow-up discussion.
Good luck and happy coding! 🚀