Bundle up work into functions

INPUT · Slides

Pulling functions together

01 / 03

The four tools you have picked up

Let us line up what this chapter taught you.

  • a function … give a lump of work a name and call it up
  • a parameter … hand a value over at the call and change what happens inside
  • a return value … carry a result home with return and use it at the caller
  • scope … how far a variable reaches. The inside sees out, but the outside does not see in

With all four in hand, you can write in the style of making parts and putting them together.

02 / 03

The order to build in

With a big problem, do not try to write it all at once. Think in this order and you will not get lost.

  • settle the output you want first … what lines, and how many of them
  • find the sums that keep coming up … that is where a function goes
  • settle the values that function needs … those are the parameters
  • settle the answer that function produces … that is the return value
  • line it up last … write the calls in order and build it up
function subtotal(price, count) {  return price * count;}console.log(subtotal(120, 4));console.log(subtotal(250, 2));

Result

480
500

03 / 03

When you get stuck, look at the values

When it does not behave as you meant, showing the values partway through is the quickest way to be sure.

Add a console.log(parameter) at the top of the function for a moment and you can see what it is catching. If undefined turns up, suspect a value you forgot to hand over or a return you forgot to write.

Errors are fine — you just fix them. Right then, ten to go at.