Arrow functions
You'll learn to read and write arrow functions, and to know when they return a value for you.
map, every click handler and many components are written this way.Watch & read
Start with the required ones. The others are there when you need them.
Explanation
You already know functions. Now you want a shorter way to write the small ones, especially the ones you
pass to map or to a button. That shorter way is called an arrow function.
Think of a shop price label. The long version says "Take the price. Add 60 taka delivery. Give back the total." The short version just says "price → price + 60". Same meaning, fewer words.
function withDelivery(price) {return price + 60;}const withDeliveryArrow = (price) => price + 60;
Both do the same job. Read the arrow one from left to right: the parameters in brackets, then =>,
then the value to give back. With one parameter you may drop the brackets: price => price + 60.
With no parameters you write empty brackets: () => "Hello".
Without { }, the value after => is returned for you. This is called an implicit return. Once
you add { }, the arrow works like a normal function body, and you must write return yourself:
const withVat = (price) => {const vat = price * 0.15;return price + vat;};
People often add { } to an arrow and forget return. Nothing crashes. The function just gives back
undefined, and a map gives a list full of undefined. A second trap: to return an object without
{ } braces for the body, wrap it in brackets: (name) => ({ name: name }).
Arrows shine as callbacks, functions you hand to someone else to call later:
const marks = [45, 72, 88];const withBonus = marks.map((mark) => mark + 5); // [50, 77, 93]
When you read an arrow, ask two things: what goes in (before =>), and is there a { }? If there is,
look for the return.
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.
1const addDelivery = (price) => { price + 60; };2console.log(addDelivery(100));
withBonus should hold every mark plus 5, and half(10) should give 5. Both arrows forget something. Fix them so all checks pass.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3What does
const half = n => n / 2;give forhalf(8)? - 2 / 3What does
const total = (a, b) => { a + b; };give fortotal(2, 3)? - 3 / 3Which arrow takes no parameters and gives back
"Hello"?
Explain it back
How confident are you with Arrow functions?
Done
{ }.