JavaScript Arrow Functions: Short Syntax and this
Arrow functions are a compact way to write functions, introduced in ES2015. They are everywhere in modern JavaScript, especially as short callbacks passed to array methods, timers and promises.
The syntax
const double = (n) => n * 2; is a function that takes n and returns n * 2. Compared with function, you drop the keyword, put => after the parameters, and, when the body is a single expression, you can drop the braces and the return too. This is called an implicit return.
- With no parameters, write empty parentheses:
() => 42. - With exactly one parameter the parentheses are optional,
n => n * 2, though many style guides keep them. - With a block body in braces, you need an explicit
return, just like a normal function.
Returning an object
() => { name: "Ava" } does not return an object: the braces are read as a block body, and name: becomes a label. Wrap object literals in parentheses: (name) => ({ name, active: true }). The { name } shorthand means { name: name }.
Expected output
42 5
{name: "Ava", active: true}
[30, 10, 20]
3Arrows as callbacks
nums.map((n) => n * 10) passes an arrow to map, which calls it once per item. This is where arrows shine: the logic sits right where it is used, with almost no syntax around it.
Arrows and this
Regular functions get their own this, decided by how they are called. Arrow functions do not; they use the this of the code around them. In the example, the arrow passed to forEach sits inside the start() method, so this.count refers to the counter object. With a regular function callback, this would not be the counter and the count would not change.
The flip side: do not use an arrow function as an object method that needs this to be the object, and arrows cannot be used with new as constructors.
Common mistakes
- Returning an object without wrapping it in parentheses.
- Adding braces and forgetting the
return:(n) => { n * 2 }returnsundefined. - Using an arrow as a method and expecting
thisto be the object.
Summary
(params) => expressionreturns the expression implicitly.- Use braces and
returnfor multi-statement bodies. - Wrap returned object literals in parentheses.
- Arrows inherit
thisfrom the surrounding code.
Quiz: Arrow functions