What is an Arrow function in JavaScript

Arrow functions are a more concise syntax for writing function expressions in JavaScript, introduced with ECMAScript 6 (ES6) in 2015. They are handy for short, simple functions and provide some differences in behavior compared to traditional function expressions.

Syntax

(parameters) => { function_body }

or, for single-parameter arrow functions, you can omit the parentheses:

parameter => { function_body }

When the function body consists of a single expression, you can use an even more concise syntax by omitting the curly braces and using an implicit return.

(parameters) => expression

Example

// Traditional function expression
const add = function (a, b) {
  return a + b;
};
console.log(add(19, 21))

// Arrow function
const addArrow = (a, b) => a + b;
console.log(addArrow(19, 21))

Output

40
40

Key differences from the traditional function expressions

No, this binding: Arrow functions do not have their value. Instead, they inherit this value from the surrounding (enclosing) scope. This is particularly helpful when working with callbacks and event listeners.

No arguments object: Arrow functions do not have the arguments object. You must use named parameters or the rest parameter syntax (…args) to access the function arguments.

No prototype property: Arrow functions do not have a prototype property, and therefore they cannot be used as constructors (i.e., they cannot be instantiated with the new keyword).

No yield keyword: Arrow functions cannot be used as generator functions, and you cannot use the yield keyword within an arrow function.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.