Skip to the workspace
Pebellslearn by building
JavaScript  ›  Lesson

Values, Variables and Functions

JavaScript 15 minJavaScript stores values such as strings, numbers, booleans, objects and arrays under names made with const or let, packages work into functions, and compares with strict equality.

frontend / Values, Variables and Functions

Explore each scene at your own pace.

01 · The rule

The rule

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

const by default, let when 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"];      // array

Variables are names for values.

  • const creates a name that cannot be pointed at a new value. Use it for most things.
  • let creates a name you can reassign, such as a running total.
  • var is 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);        // 378

The 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.