Bundle up work into functions

INPUT · Slides

Using a return value where it stands

01 / 04

You do not have to park it in a variable

You have been writing const t = add(3, 5); console.log(t);, but add(3, 5) is a value in its own right. You can use it without going through a variable.

Picture the place where you wrote add(3, 5) being replaced by 8. Anywhere you could write a number or a string, you can write this.

function add(a, b) {  return a + b;}console.log(add(3, 5) + 100);console.log(`total ${add(3, 5)} yen`);

Result

108
total 8 yen

02 / 04

Put it in an if condition

Make a function that sends back true or false and you can write it straight into an if condition.

The nice part is that the meaning of the condition becomes readable from the function's name. if (isEven(n)) tells you what is being checked at a glance, where if (n % 2 === 0) does not.

function isEven(n) {  return n % 2 === 0;}for (let i = 1; i <= 4; i++) {  if (isEven(i)) {    console.log(`${i} even`);  } else {    console.log(`${i} odd`);  }}

Result

1 odd
2 even
3 odd
4 even

03 / 04

Hand a function's result to a function

A return value is a value, so it can be another function's argument. Write double(double(3)) and it works out from the inside.

  • the inner double(3) becomes 6
  • the outer becomes double(6), which is 12

Nesting works from the inside. Read it from the inside too.

function double(n) {  return n * 2;}console.log(double(double(3)));console.log(double(5) + double(10));

Result

12
30

04 / 04

Put small functions together

A function does not have to do everything on its own. Making them small and putting them together is easier both to fix and to read.

  • a function that works out the postage
  • a function that works out the line total
  • a line that adds those two and shows it

Split like that, a change to the postage rule means changing one place only. From here you can put a program together yourself. Write and see.

function shipping(total) {  if (total >= 1000) {    return 0;  }  return 300;}const price = 800;console.log(`to pay ${price + shipping(price)} yen`);

Result

to pay 1100 yen