Values, Variables and Functions
HTML gives the bakery page structure and CSS gives it looks. JavaScript gives it behaviour: adding a loaf to an order, updating the total, showing "Sold out". Before touching the page, you need the three building blocks every script is made of: values, the names you store them under, and functions that do work with them.
The rule
constby default,letwhen it must change, and always compare with===.
Values come in a handful of types:
const name = "Country sourdough"; // string
const price = 180; // number (whole or decimal)
const inStock = true; // boolean
let note = null; // deliberately empty
let discount; // undefined: no value yet
const loaf = { name: "Rye", price: 150 }; // object
const basket = ["Rye", "Bun", "Bun"]; // arrayVariables are names for values.
constcreates a name that cannot be pointed at a new value. Use it for most things.letcreates a name you can reassign, such as a running total.varis the older keyword with looser rules; avoid it in new code.
const fixes the name, not the contents. basket.push("Rye") still works on a const array, because the variable keeps pointing at the same array.
Functions package a piece of work so you can reuse it:
function lineTotal(price, quantity) {
return price * quantity;
}
const withTax = (amount) => amount * 1.05;
lineTotal(180, 2); // 360
withTax(360); // 378The first is a function declaration; the second is an arrow function, a shorter form used a lot for small helpers and event handlers. return sends the result back; a function without return gives back undefined.
Comparing values. === checks that two values are equal and of the same type. The older == converts types first, which leads to surprises: 0 == "" is true, while 0 === "" is false. The same conversion trap hides in +: when either side is a string, + joins text, so "5" + 1 is "51", not 6.
The shortcut
For every name you create, ask "Will this name ever need to point at something else?" No: const. Yes: let. For every comparison, type three equals signs without thinking about it.
Fixed things
The price list and the basket array never get replaced, only read or added to:
const prices,const basket.
A common slip is reaching for let everywhere "just in case". Every let tells the reader that the value might change later, so they have to track it. A page full of const is easier to trust, because each name means one thing from start to finish.
Drills
Answer fast — trust the rule.
What happens when this runs? const total = 3; total = 4;
What is "5" + 1 in JavaScript?
What does 0 === "" evaluate to?
const basket = ["Rye"]; basket.push("Bun"); What is basket afterwards?
What does calling function greet() { "Hello"; } return?
Remember
constby default,letwhen it must change, and always compare with===.- Ask: will this name ever point at something else?
- Trap:
constdoes not freeze an array's contents, and+with a string joins text.
