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.