When compared to traditional functions, arrow functions make code concise and expressive, and require less typing. However, they are not simple replacements for anonymous functions—significant semantic differences exist between anonymous functions and arrow functions. In this chapter you learned about the benefits and the limitations of arrow functions, how to create them, and when to use them. You also saw how arrow functions reduce noise when creating functional style code. In the next chapter, we’ll explore one of the most charming features of modern JavaScript—destructuring.
Use the following exercises to review the differences between anonymous functions and arrow functions. You can find answers to these exerciseshere.
Does JavaScript use lexical scoping or dynamic scoping for anonymous functions? How about for arrow functions?
Refactor the following code to make it concise and to use arrow functions.
| 'use strict'; |
| |
| const success = function(value) { |
| return { value: value }; |
| }; |
| |
| const blowup = function(value) { |
| throw new Error('blowing up with value ' + value); |
| }; |
| |
| const process = function(successFn, errorFn) { |
| const value = Math.round(Math.random() * 100, 2); |
| |
| if(value > 50) { |
| return successFn(value); |
| } else { |
| return errorFn(value); |
| } |
| }; |
| |
| try { |
| console.log(process(success, blowup)); |
| } catch(ex) { |
| console.log(ex.message); |
| } |
Make an effort to convert the following function to an arrow function:
| 'use strict'; |
| |
| const greet = function(...names) { |
| console.log(this + ' ' + names.join(', ')); |
| }; |
| |
| const helloJackJill = greet.bind('hello', 'Jack', 'Jill'); |
| |
| helloJackJill(); //hello Jack, Jill |
What’s wrong with this code? Fix it so the code produces the correct/desired result.
| 'use strict'; |
| |
| const sam = { |
| name: 'Sam', |
| age: 2, |
| play: (toy) => 'I am ' + this.name + ', age ' + this.age + ' with ' + toy |
| }; |
| |
| console.log(sam.play('ball')); |
Rewrite the following imperative code to functional style.
| 'use strict'; |
| |
| const numbers = [1, 5, 2, 6, 8, 3, 4, 9, 7, 6]; |
| |
| let totalOfDoubleOfEven = 0; |
| |
| for(const number of numbers) { |
| if(number % 2 === 0) { |
| totalOfDoubleOfEven += number * 2; |
| } |
| } |
| |
| console.log(totalOfDoubleOfEven); |