Bundle up work into functions

INPUT · Slides

Handing a value to a function

01 / 05

You want different results from the same function

When you made that greeting function, you probably wanted to change just the name part. "good morning, Yui", "good morning, Haruto", and so on.

Making one function per name would be hard work. So instead we use the machinery for handing a value in when you call. A value handed in like that is called an argument, and the name that catches it a parameter.

02 / 05

The shape of a parameter

Write the name that catches it inside the brackets of the definition, and the value to hand over inside the brackets of the call.

When you call it, the value you handed over goes into that name, and inside the { } you can use it like any ordinary variable.

function greet(name) {  console.log(`good morning, ${name}`);}greet("Yui");greet("Haruto");

Result

good morning, Yui
good morning, Haruto

03 / 05

Numbers can go in too

It is not only strings you can hand over. Numbers, true and false, a value sitting in a variable — all fine.

What you hand over can be used in sums inside the { }. One set of contents, and as many results as there are values to hand in.

function showTotal(count) {  console.log(`${count} for ${count * 150} yen`);}showTotal(2);showTotal(5);

Result

2 for 300 yen
5 for 750 yen

04 / 05

The catching name belongs to the function alone

The name in function greet(name) is a name usable only inside this function. Write name outside and it will not reach.

You choose the name yourself. greet(who) behaves the same. Pick one that says what the value stands for inside.

Have a look at what happens if you forget to hand anything over, too. No value arrives, so you get undefined.

function greet(name) {  console.log(name);}greet("Sora");greet();

Result

Sora
undefined

05 / 05

The same in an arrow function

Arrow functions are written no differently. You just write the catching name inside the ().

That gives you the flow "hand it over, use it inside". Get your hands moving and it will settle in.

const shout = (word) => {  console.log(`${word}!!`);};shout("yes");shout("done it");

Result

yes!!
done it!!