DEV Community

Ishan Bagchi
Ishan Bagchi

Posted on

Arrow functions: All you need to know!

An arrow function is an alternative to a traditional function expression, but is limited and can't be used in all situations.

Syntax of an arrow function

const foo = (arg1, arg2, ..., argN) => expression
Enter fullscreen mode Exit fullscreen mode

Some examples:

Add two numbers

// Arrow function
const addArrow = (number1, number 2) => number1 + number2

// Traditional function
let addTraditional = function(a, b) {
  return a + b;
};

console.log(addArrow(5 , 7)) // 12
console.log(addTraditional(5 , 7)) // 12
Enter fullscreen mode Exit fullscreen mode

Multiline functions

We have to add curly braces if there is more than 1 line in a function.

let add = (number1, number2) => {  // the curly brace opens a multiline function
    let result = number1 + number2;
    return result; // if we use curly braces, then we need an explicit "return"
};
Enter fullscreen mode Exit fullscreen mode

One argument function

If only one argument is passed through the function, the braces can be omitted.

let add = number => number + 10

console.log(add(5)) // 15
Enter fullscreen mode Exit fullscreen mode

Limitations of arrow functions:

  • Does not have its own bindings to this or super, and should not be used as methods.
  • Does not have arguments or new .target keywords.
  • Not suitable for call, apply, and bind methods, which generally rely on establishing a scope.
  • Can not be used as constructors.
  • Can not use yield, within its body.

I have mentioned the surface level facts of arrow functions. For more information visit the official arrow function doccumentation of MDN.

Top comments (0)