Bundle up work into functions

INPUT · Slides

Giving work a name

01 / 05

You keep writing the same steps

As you write programs, you keep running into places where you want exactly the same few lines again.

Copy and paste works for now. But when you want to change it, you have to change every place you pasted it. Miss one and that one stays on the old behaviour.

That is what a function is for. It is the machinery for giving a lump of work a name and calling it up by that name.

02 / 05

The shape of function

Write function name() { work } and what is inside the { } gets a name. That is defining a function.

Defining it does not make anything happen. Write name() to call it and only then does the inside run.

function greet() {  console.log("good morning");}greet();

Result

good morning

03 / 05

It runs as many times as you call it

Define it once and you can call it as often as you like. Instead of three console.log lines, you write three calls.

And when you want to change what it does, you change the one place you defined it and every call follows.

function ring() {  console.log("clang");}ring();ring();ring();

Result

clang
clang
clang

04 / 05

You can write as many lines inside as you like

Inside a function's { } you can write anything you have learned. Loops and branches go in too.

However many lines there are, from the caller's side it is one name. Being able to use it without minding what happens inside is the nice thing about a function.

function showMenu() {  console.log("=== TODAY'S MENU ===");  for (let i = 1; i <= 3; i++) {    console.log(`dish ${i}`);  }}showMenu();

Result

=== TODAY'S MENU ===
dish 1
dish 2
dish 3

05 / 05

The call is easy to forget

A common stumble is defining it and never calling it. When nothing shows up, check first that there is a name() line.

The knack with names is to make the contents guessable. Read showMenu and you think "ah, it puts the menu out".

Right then, define one and call it.