Chapter 5

Here are the solutions to the Exercises, for the Chapter 5, Arrow Functions and Functional Style chapter.

Exercise 1

For anonymous functions, this and arguments are dynamically scoped and other non-local, non-parameter variables are lexically scoped.

For arrow functions, all non-local, non-parameter variables are lexically scoped.

Exercise 2

Here’s a solution to make the code concise and to use arrow functions:

 'use strict'​;
 
 const​ success = value => ({ value: value });
 
 const​ blowup = value => { ​throw​ ​new​ Error(​'blowing up with value '​ + value); };
 
 const​ process = ​function​(successFn, errorFn) {
 const​ value = Math.round(Math.random() * 100, 2);
 
 return​ value > 50 ? successFn(value) : errorFn(value);
 };
 
 try​ {
  console.log(process(success, blowup));
 } ​catch​(ex) {
  console.log(ex.message);
 }

Keep process() as a regular function instead of a multiline arrow function, which does not offer much benefit.

Exercise 3

The given function, greet(), relies on this, which makes it harder to convert to arrow functions. We can rework the function as follows:

 'use strict'​;
 
 const​ greet = (message, ...names) =>
  console.log(message + ​' '​ + names.join(​', '​));
 
 const​ helloJackJill = greet.bind(​null​, ​'hello'​, ​'Jack'​, ​'Jill'​);
 
 helloJackJill(); ​//hello Jack, Jill

Exercise 4

The output for the given code is

 I am undefined, age undefined with ball

The function play() needs this in dynamic scope, the object on which it is called. Don’t use an arrow function as an instance method. Here’s the fix:

 'use strict'​;
 
 const​ sam = {
  name: ​'Sam'​,
  age: 2,
  play: ​function​(toy) {
 return​ ​'I am '​ + ​this​.name + ​', age '​ + ​this​.age + ​' with '​ + toy;
  }
 };
 
 console.log(sam.play(​'ball'​));

The output of this modified code is

 I am Sam, age 2 with ball

Exercise 5

From imperative to functional, using the higher-order functions in an array:

 'use strict'​;
 
 const​ numbers = [1, 5, 2, 6, 8, 3, 4, 9, 7, 6];
 
 console.log(
  numbers.filter(e => e % 2 === 0)
  .map(e => e * 2)
  .reduce((total, e) => total + e));
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset