Step 1 of 7 · Reading · ~4 min
Learn
Functions
Arrow Functions
Arrow functions are a short way to write a function, written =>. By the end of this lesson you can read and write every arrow form, and you can write a function that takes or returns another function.
The forms
The rule behind the short form: if the body is a single expression with no braces, that expression is the return value. The moment you add braces, you are writing a normal function body and need return yourself:
Returning an object
An object is a bundle of named values written { name: value }; the objects lesson covers them. Braces after => are read as a function body, so an object literal needs parentheses around it:
Functions as values
A function is a value like a number. You can pass one to another function, and one function can return another. This is the main reason arrows exist:
A function that returns a function uses two arrows in a row. Read a => b => expr as "takes a, returns a function that takes b":
addFive still remembers n was 5 after adder has finished. That behaviour has a name, closure, which has its own lesson later; for now just notice that it works.
You will also hand arrows to array methods such as map and filter very soon (an array is a list in square brackets; map builds a new list by calling the arrow on every item):
What arrows leave out
Arrows are not a drop-in replacement for every function:
regular function | arrow | |
|---|---|---|
own this | yes, set by how it is called | no, uses the this around it |
arguments object | yes | no (use ...args) |
can be called with new | yes | no |
| can be used before its line | yes (declarations) | no |
The this difference matters when you attach a function to an object: a method that needs this should be written in normal method form, { greet() { ... } }, not as an arrow. The full story is in the intermediate course; the safe rule for now is arrows for small helpers and callbacks, normal functions for methods.
Common mistakes
- Adding braces to a one-expression arrow and forgetting
return, so the function returnsundefined. - Returning an object literal without wrapping it in parentheses.
- Writing
x, y => x + y; two parameters need parentheses. - Misreading
a => b => c: the first call returns a function, sof(1)alone is not the final value. - Using an arrow as an object method that needs
this.
Your exercise
Combine functions. The starter has two small arrows and one that builds a new function out of two others, all with placeholder bodies. The program at the bottom uses them and prints two lines.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…