Javascript - Function Arrow Functions

Introduction

Arrow functions are functions defined using a new syntax, the "fat" arrow =>.

The arrow syntax removes the function and return syntax.

The basic syntax of an arrow function is as follows:

var fn = data => data; 

The function is effectively equivalent to

var fn = function(data) { 
    return data; 
}; 

Consider another example:

let getNumber = () => 42; 

console.log(typeof getNumber); // function 
console.log(getNumber()); // 42 

Here, we declare a new function called getNumber and assign it using an arrow function.

The empty parentheses () denotes that the function has no parameters.

In arrow functions, we can leave out the return keyword.

The expression specified after the arrow will get returned as long as it is not wrapped in { }.

var getPrice = (count, tax) => (count * 5) * (1 + tax); 
console.log(getPrice(2, .095)); //  10.95 

To use code block with more than one expression, wrap the body in braces.

You need to use the return keyword to specify the return value.

var getPrice = (count, tax) => { 
    let price = (count * 5);
    price *= (1 + tax); 
    return price; 
} 

console.log(getPrice(2, .095)); //  10.95 

To return an object literal from the arrow function, wrap the literal in parentheses.

An object literal wrapped in parentheses is an object literal instead of the function body.

var getNumber = data => ({ 
   data: "check", 
   number: 42 
}); 

// effectively equivalent to: 

var getNumber = function(data) { 
    return { 
        data: "check", 
        number: 42 
    }; 
}; 

Related Topics