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 second project in this practice session and see how to modify properties on a simple object literal.
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
Code for completed solution
let product = {
name: "Chair",
inventory: 10,
unit_price: 45.99
};
function addInventory(prod, quantity) {
prod.inventory += quantity;
console.log(quantity + " " + prod.name + "s added to the inventory.");
console.log(prod.inventory + " " + prod.name + "s in stock.");
}
addInventory(product, 3);
function processSale(prod, quantity) {
prod.inventory -= quantity;
console.log(quantity + " " + prod.name + "s sold");
return quantity * prod.unit_price;
}
console.log("Total sale: $" + processSale(product, 3));
You need to sign up for Treehouse in order to download course files.
Sign up