Arrow functions
The task: take Project 2 and rewrite every function as an arrow function. Watch one function change in four steps, then run the refactored code.
Sklyarenko Vlad
One function, four steps
Pick a step. The yellow marks show exactly what changed since the step before.
Project 2, rewritten
Same four animals, same two buttons as in Project 2. Now First, Go, Second and Go2 are all arrow functions. Click an animal to hear it.
This is the code from the lecture. On this page it is written with const in front of each name (const First = () => {…}). Without const the name becomes an accidental global variable, and strict mode refuses it. The unused var k = 0 from Project 2 is dropped again.
The objects need a small change too
In Project 2 the animals were made with new Animal(...). A constructor cannot be an arrow function, so the arrow version is a factory: a function that returns an object.
The parentheses around { … } matter. Without them JavaScript reads the braces as a function body, not as an object.
Arrow function or function?
| function | arrow => | |
|---|---|---|
| Syntax | longer, has the function keyword | short, one expression needs no braces or return |
Use with new | yes, it can be a constructor | no, it throws a TypeError |
Its own this | yes, set by how it is called | no, it uses the this around it |
| Hoisting | a declaration can be called before the line that defines it | only after the line that defines it |
Try it: new
The same constructor written both ways. Press the button and read what the browser says.
Try it: this
A cat object with two methods. One is a normal method, one is an arrow function. Both ask: who is this?
Arrow syntax cheat sheet
- One parameter
The parentheses are optional:
x => x * 2. - One expression
No braces and no
return: the value of the expression is returned. - Returning an object
Wrap it in parentheses:
() => ({ a: 1 }).
Good places for arrows, and places to avoid them
Use them for short callbacks such as forEach, map and filter, and for small helpers. Avoid them for constructors and for methods that need their own this.