Functions in, values out
You'll learn to write functions that take values in and give a value back with return.
Watch & read
Start with the required ones. The others are there when you need them.
Explanation
You want to work out the same thing many times: a price plus delivery, for each order. Instead of writing the sum again and again, you give the steps a name once, and use that name whenever you need it. A named set of steps is called a function.
Think of a tea stall. You hand over money and a cup size, and you get tea back. What you hand over goes in; one thing comes out.
function withDelivery(price) {return price + 60;}const total = withDelivery(200); // 260
price is a parameter: the name the function uses for the value it receives. 200 is the
argument: the real value you pass when you call the function. return sends a value back to
the caller, and the function stops right there.
return and console.log are not the same. console.log only prints for you to see. return
gives the value back so the rest of your code can use it. People often write console.log inside a
function and then wonder why const total = ... is undefined. A function with no return gives back
undefined.
You'll also see a shorter way to write a function, called an arrow function:
const withDelivery = (price) => price + 60;
It does the same job. With no { }, the value after => is returned for you. With { }, you must write
return yourself.
When you read a function, find three things: what goes in (the parameters), what it does, and what it returns.
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1function double(n) {2 console.log(n * 2);3}4const result = double(5);5console.log(result);
withDelivery should give back the price plus 60 taka delivery, so other code can use the result. Fix it so all three checks pass.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3In
function greet(name) { ... }andgreet("Nusrat"), which is the argument? - 2 / 3What is
resultafterfunction add(a, b) { console.log(a + b); }andconst result = add(2, 3);? - 3 / 3What does
const half = (n) => n / 2;give forhalf(10)?
Explain it back
How confident are you with Functions in, values out?
Done
return apart from console.log.