DEV Community

Ishan Bagchi
Ishan Bagchi

Posted on

4

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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →