Arrow Functions
An arrow function is JavaScript's lambda, written (a, b) => a + b, almost exactly like C#. One parameter needs no parentheses, a body in braces needs a return, and an object returned on its own needs parentheses around it.
Apprentice · JavaScript · Updated
After this lesson you can
- Write arrow functions with zero, one or more parameters, and with an expression or a block body
- Pass arrow functions to other functions as callbacks
Key takeaways
- An arrow function is JavaScript's lambda, written almost exactly like C#:
(a, b) => a + b. - One parameter needs no parentheses, as in
n => n * 2; none, or more than one, need them. - An expression body is returned by itself. A block body in braces needs a
return, or the function returnsundefined. - To return an object literal from an arrow function, wrap it in parentheses:
name => ({ name: name, active: true }). - A callback is a function passed to another function to be called later, such as the arrow function you hand to
filterorsetTimeout.
You already know arrow functions: they're C# lambdas, with the same arrow. In JavaScript, the arrow is written => too, and it's read the same way.
| C# lambda | JavaScript arrow function |
|---|---|
x => x * 2 |
x => x * 2 |
(a, b) => a + b |
(a, b) => a + b |
() => Console.WriteLine("Hi") |
() => console.log('Hi') |
The forms
const double = n => n * 2;
const add = (a, b) => a + b;
const sayHi = () => console.log('Hi!');
const describe = (name, age) => {
const years = age === 1 ? 'year' : 'years';
return `${name} is ${age} ${years} old`;
};
console.log(double(21));
console.log(add(2, 3));
sayHi();
console.log(describe('Rex', 1));
console.log(describe('Bella', 4));
42
5
Hi!
Rex is 1 year old
Bella is 4 years old
- One parameter: no parentheses needed:
n => n * 2. - None, or more than one: parentheses:
() => ...,(a, b) => .... - An expression body, after the arrow, is returned by itself: no
return, no braces. - A block body, in braces, can hold several statements, and needs a
returnto give anything back. Forget it, and the function returnsundefined.
An arrow function stored in a const is used exactly like a function declared with function. Many JavaScript developers write all their small functions this way.
Returning an object
One trap. Braces after the arrow mean a block body, so to return an object literal, wrap it in parentheses:
const toPerson = name => ({ name: name, active: true });
const person = toPerson('Ada');
console.log(person.name, person.active);
Ada true
Without the parentheses, the braces are read as a block: name => { name: name } returns undefined, and name => { name: name, active: true } doesn't even run: it's a SyntaxError. (console.log with two arguments prints them with a space between.)
Callbacks
Arrow functions are at their best as callbacks: small functions passed to another function, to be called later. Every array method in the last lesson took one:
const products = [
{ name: 'Coffee', price: 3.5 },
{ name: 'Tea', price: 2.75 },
{ name: 'Bagel', price: 2.25 }
];
const cheap = products
.filter(p => p.price < 3)
.map(p => p.name.toUpperCase());
console.log(cheap.join(', '));
const total = products.reduce((sum, p) => sum + p.price, 0);
console.log(total.toFixed(2));
setTimeout(() => console.log('Half a second later'), 500);
console.log('Waiting...');
TEA, BAGEL
8.50
Waiting...
Half a second later
- The
filter,mapandreducechain is LINQ again, with arrow functions for the lambdas.toFixed(2)formats a number with two decimal places, like:0.00. setTimeouttakes a callback and a time in milliseconds, and calls the callback later. Meanwhile, the program carries on: Waiting... prints first. That's how a browser runs your code when a button is clicked: you hand it a callback, and it calls it when the time comes.
Check yourself
2 questions to try on the lesson page.
So what
Arrow functions are the lambdas you already write in C#, under the same arrow. Use the short form for one-liners, braces and return for more, and hand them to any function that wants a callback.