Arrow functions

Arrow functions are modern JS syntax to declare a function, which is introduced in ES6. Besides a shortes syntax, below are the properties:

  • Arrow functions don’t have their own bindings to this, arguments, or super, and should not be used as methods.
  • Arrow functions cannot be used as constructors. Calling them with new throws a TypeError. They also don’t have access to the new.target keyword.
  • Arrow functions cannot use yield within their body and cannot be created as generator functions.

A good suggestion from developer Lars Schöning:

  1. Use function in the global scope and for Object.prototype properties.
  2. Use class for object constructors.
  3. Use => everywhere else.

Syntax

(param1, paramN) => expression

(param1, paramN) => {
  statements
}

let/const variableName = (argument) => {function body}

Example for function with no arguments

When having no arguments, you have to use empty parentheses in the function decalaration. When returning a single value, no need of curly brackets and return keyword.

// Traditional function
function randomNumber() {
    return Math.random();
}

console.log(randomNumber());

// Arrow function syntax
let randomNumber2 = () =>  Math.random();
console.log(randomNumber2());

// Traditional function with parameter as fn
document.addEventListener('click', function() {
    console.log('click')
})

// Arrow function with parameter as fn
document.addEventListener('click', () => console.log('click'))

Example for function with only one argument

When having exactly one argument, you may omit the parentheses.

function isPositive(number){
    return number >= 0
}

let isPositive2 = number => number >= 0;
console.log(isPositive2(3));

const multiply = number => number * 2;
console.log(multiply(3));

Example for Function with more than one arguments

function sum(a, b){
    return a+ b;
}

const sum2 = (a,b) => { 
  return a+b;
};
console.log(sum2(10,100));
References

MDN Docs
scaler


Read More