Defining the product list
Set up the cart foundation with arrays of product names and prices.
Two parallel arrays
We'll use two parallel arrays to represent products:
productNames: holds product names (strings)productPrices: holds product prices (numbers)
Items at the same index belong to the same product: productNames[0] and productPrices[0] give the first product's name and price.
This structure is called parallel arrays; we choose it here because it keeps things simple instead of using a single object.
Accessing array elements
You access an array element by its index. Indexes start at zero and the last index is length - 1:
productNames[0]→ first product's nameproductNames[1]→ second product's nameproductNames[2]→ third product's name
The same applies to productPrices. Inside a for loop, you can use the i variable as the index to reach every element in turn.
Exercise Define the product names and prices arrays
In the previous step you declared an empty cart array. Now add two new arrays: productNames with three product names, productPrices with three prices in the same order. Then print both with console.log.
Show example solution
// Empty array for the cart
const cart = [];
// Product names and prices
const productNames = ["Pen", "Notebook", "Eraser"];
const productPrices = [15, 30, 10];
console.log(productNames, productPrices);
Test yourself
-
Complete the array literal syntax
const productNames = ____; console.log(productNames[0]);Show answer
const productNames = ["Pen", "Notebook", "Eraser"]; console.log(productNames[0]); -
What is the type of the value 30 in const productPrices = [15, 30, 10];?
- string
- number
- boolean
- array
Show answer
number — Correct! Numbers without quotes are of type number.
-
Match the index to its value
- productNames[0]
- Pen
- productNames[1]
- Notebook
- productNames[2]
- Eraser
- productPrices[0]
- 15