1function total(price, count) {2 const cost = price * count;3 return cost;4}5const tea = total(3, 4);6const cake = total(5, 2);7console.log(tea + cake);Consolepricecountcost
Code card: the script; highlighted lines are the ones the step is aboutMemory boxes: the global names total, tea and cakeCall frame: appears for each call, holds the local variables price, count and cost, then is clearedConsole: where console.log printsEach step lights the lines it is about. A call lights the calling line and the function's first line, and a token carries the arguments up into the function while a call frame tray appears with the local variables price, count and cost. A return carries the answer back down to the line that called, and the tray is cleared away. The same lines of total run for both calls, with different arguments, and give 12 and 10; console.log(tea + cake) prints 22. The drawing shows each call’s local variables on a tray, the call frame. The ECMAScript specification calls it an execution context: every call gets a new one with its own record of local names, it goes on the call stack, and it is removed when the call returns.

Define

  1. The function keyword creates a function: a named list of steps. JavaScript stores it under the name total before any line runs. Lines 2 and 3 do not run yet. price and count are parameters: names for values a caller hands in.

First call

Second call

Why functions

What happens

// step 1/11 · define
line 1   function total(price, count) {
makes    a function named total
         and stores it before line 1 runs
params   price, count  (filled in by each call)
body     lines 2 and 3: saved, not run
typeof total   →  "function"

The drawing shows each call’s local variables on a tray, the call frame. The ECMAScript specification calls it an execution context: every call gets a new one with its own record of local names, it goes on the call stack, and it is removed when the call returns. A function that ends without a return statement, or with a bare return;, sends back the value undefined.