Bundle up work into functions

INPUT · Slides

Sending a result back out of a function

01 / 05

Showing it is not enough to carry on with

Every function so far did a console.log inside and finished. But that leaves you unable to use the result afterwards.

Make a function that works out a total and you still cannot add postage to that total, or compare it in a condition.

The word for carrying a result back to where you called from is return.

02 / 05

The shape of return

Write return value; and that value goes back to where you called from. A value that comes back like that is called a return value.

It helps to think of the place where you wrote add(3, 5) being replaced by 8. Which is why you can put it in a variable, or show it directly.

function add(a, b) {  return a + b;}const total = add(3, 5);console.log(total);console.log(add(10, 20));

Result

8
30

03 / 05

No return means undefined

Call a function with no return in it and the return value is undefined. It means "no value to send back has been settled".

Doing the sum but not sending it back is a common thing to forget. When your result comes out undefined, check first that there is a return.

function add(a, b) {  a + b;}console.log(add(3, 5));

Result

undefined

04 / 05

Once you return, that is the end

When a return runs, the function finishes there and then. Lines left below it do not run.

Use that and you can write a function that sends back a different value per case. Even without an else, returning first means you never get to what is below.

function judge(score) {  if (score >= 60) {    return "pass";  }  return "fail";}console.log(judge(72));console.log(judge(40));

Result

pass
fail

05 / 05

A function that shows, and a function that sends back

A function that does a console.log, and a function that does a return. These two have different roles.

  • a function that shows … its job is to put things on the screen. It carries nothing back
  • a function that sends back … its job is to work something out. It leaves the showing to the caller

The one that sends back gets reused more. If you want it shown, you only have to write console.log(add(3, 5)).

Right then, let us write some that send back.