Back to Vlad
Project 3

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

Sklyarenko Vlad

01 · Refactoring

One function, four steps

Pick a step. The yellow marks show exactly what changed since the step before.


  
02 · 3.html

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.

03 · Compare

Arrow function or function?

functionarrow =>
Syntaxlonger, has the function keywordshort, one expression needs no braces or return
Use with newyes, it can be a constructorno, it throws a TypeError
Its own thisyes, set by how it is calledno, it uses the this around it
Hoistinga declaration can be called before the line that defines itonly 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?

04 · Shortcuts

Arrow syntax cheat sheet

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.

Web hosting by Somee.com