Week 3 Follow-Up: a Few Quick Exercises to Make You More Comfortable with Javascript

These four exercises are designed to reinforce some of the important concepts we covered in class. The boilerplate code can be found here (fork and clone please!)

Imagine a list of products, say shoes, on a website like Amazon:

Underlying this is a data structure that is a list (array), and each item in the list is a product (object), and each object has many properties (price, manufacturer, name, reviews etc.) This assignment will allow you to practice manipulating these data structures.

3.1 Creating objects, and adding them to the array

Create 4 objects representing the sneaker products we have up above, and include the product name, manufacturer, and price properties. Since price is a range, use the upper end.

Once an object is created, you can add it to the array using array.push()

productList.push(newProduct); //newProduct is an object
Arrays and objects are two of the most important Javascript constructs we will be using. If you have time, quickly peruse the API documentation for arrays here.

3.2 Iterate over arrays

How many of these sneakers are under $50? This problem can be broken down as follows.

  1. Iterate over the entire length of the array (for loop) — I’ve already done this part for you.
  2. With each item in the array, check to see if the price is below $50 (if statement).
  3. If true, console.log() a message.
This step combines the for loop, the if statement, and string operations

3.3 Calculate average price of all sneakers in the list

Again, try to break this down into smaller problems:

  1. First, you need to sum up all the prices in the list; this involves a for loop again;
  2. Then, you divide total price by the number of items in the list. A quick hint:
productList.length

will return the number of items in the list. .length is a property of any array.

3.4 Write a price comparison function

This function accepts one argument, price, and returns the number of products that is below that price.

Can you try to figure this out?

Recap

Make sure you are comfortable with the following tasks:

  1. Creating an object, and accessing and modifying its properties
  2. Creating an array, and adding objects to it
  3. If statement
  4. for loop
  5. Creating a function
Like what you read? Give Siqi Zhu a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.