Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Walk through the solution to the third project in this JS practice session and see how to create a JavaScript array of object literals.
Correction
In the video, the practice file shown says the object must have 4 properties. You only need the 3 properties: name
, inventory
, and unit_price
for each object literal.
Code for completed solution
let products = [
{
name: "chair",
inventory: 5,
unit_price: 45.99
},
{
name: "table",
inventory: 10,
unit_price: 123.75
},
{
name: "sofa",
inventory: 2,
unit_price: 399.50
}
];
function listProducts(prods) {
let product_names = [];
for (let i=0; i<prods.length; i+=1) {
product_names.push(prods[i].name);
}
return product_names;
}
console.log(listProducts(products));
function totalValue(prods) {
let inventory_value = 0;
for (let i=0; i<prods.length; i+=1) {
inventory_value += prods[i].inventory * prods[i].unit_price;
}
return inventory_value;
}
console.log(totalValue(products));
let
and const
JavaScript used to have only one keyword for creating a variable: var
. For example, to create a variable named temperature with a value of 98.9 you could do this:
var temperature = 98.9
.
Two new keywords were introduced in ES2015 (a newer version of JavaScript): let
and const
. Most JavaScript programmers now use those two keywords. However, var
works and you'll still see it around a lot. To get familiar with these keywords follow these rules:
const
Use const
(which is short for constant) to store a value that won't change. For example, if you're setting the sales tax rate -- which won't change while your program is running you'd use const
. For example:
const taxRate = 7.5;
let
Use let
to store a value that changes while the program runs. For example, if you're keeping track of a changing score, or the number of times a person clicks on a web page, use let
:
let totalSales = 0;
As with var
you can store any type of data in a variable defined with let
or const
-- numbers, strings, arrays, objects, Boolean values, etc. If you are confused about whether to use let
or const
the rule of thumb is if you're in doubt, use const
.
To learn more, check out the workshop Defining Variables with let and const
You need to sign up for Treehouse in order to download course files.
Sign up