Define
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
Line 5 calls total with the arguments 3 and 4. JavaScript pauses line 5, remembers where it was, and jumps into total. A new call frame appears: scratch space for this one call.
The arguments are matched to the parameters in order: price = 3 and count = 4. These names live in the call frame. They are local variables: they exist only inside this call.
Line 2 works out price * count: 3 * 4 is 12. const cost makes one more local variable, in the same frame, and stores 12 in it. Code outside total cannot see cost.
return cost ends the call and sends the value 12 back to line 5, exactly where the call was made. The call is over, so its frame is cleared away.
Line 5 carries on where it paused. total(3, 4) has become the value 12, so const tea = 12. price, count and cost are gone: console.log(cost) here would stop with a ReferenceError.
Second call
Line 6 calls total again, with 5 and 2. The highlight jumps into the same lines. A brand-new frame appears with price = 5 and count = 2; nothing is left over from the first call.
Lines 2 and 3 run again with the new values: cost = 5 * 2, which is 10. return sends 10 back to line 6, the line that made this call, and this frame is cleared away too.
Line 6 finishes: cake = 10. The function behaved like a small machine. Values went in as arguments, one value came out with return, and its scratch space vanished afterwards.
Why functions
Line 7 works out tea + cake, which is 12 + 10 = 22, and console.log prints it in the console. console.log is a function too, one the browser and Node.js already provide. You call it the same way.
Two answers, but the steps were written once. Without a function you would repeat price * count everywhere you need it. With one, a fix inside total fixes every call at once.
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.