Search⌘ K
AI Features

Solution Review: Refactor the Code

Explore how to refactor JavaScript code by applying arrow functions and functional programming styles. Understand the benefits and limitations of arrow functions, including syntax rules and exceptions, to write cleaner and more concise code.

Solution

The solution to the previous challenge is given below. Let’s have a look.

Javascript (babel-node)
'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);
}

Explanation

We will cover each function one by one in the top to bottom order. Let’s start with the function success().

success()

In arrow functions, the keywords function and return are not required. Hence, the code is more concise and the noise is ...