Arrow Function in JavaScript

Arrow functions were introduced in ES6(2015) as a more concise way to write functions.

It is called an arrow function because it uses an arrow (=>) of an equal sign and a greater-than character, Instead of the function keyword.

JavaScript
const a = () => {};

Do not confuse with the greater-than-or-equal operator, which is written >=.

Arrow functions instantiate objects that behave similarly to their formal function expression counterparts. Anywhere a function expression can be used, an arrow function can also be used.

JavaScript
const arrowFunction = (a, b) => {
  return a + b;
};

const expressionFunction = function(a, b) {
  return a + b;
};

console.log(arrowSum(10, 20)); //πŸ‘‰ 30
console.log(expressionFunction(10, 20)); //πŸ‘‰ 30

The arrow comes after the list of parameters and is followed by the function’s body. It expresses something like β€œthis input (the parameters) returns this result (the body)”.

Arrow functions are incredibly useful in inline situations where they offer a more concise syntax.

JavaScript
const nums = [1, 2, 3];

// Function Expression
console.log(nums.map(function(i) { return i })); //πŸ‘‰ [1, 2, 3]

//Arrow Function
console.log(nums.map((i) => { return i })); //πŸ‘‰ [1, 2, 3]

You can omit the parentheses if you only want to use a one parameter. If you do not have parameters or multiple parameters, parentheses are required.

JavaScript
// βœ… Both are valid
const a = (x) => { return x; };
const b = x => { return x; };

// ❌ Invalid syntax:
const sum = a, b => { return a + b; };

Arrow functions can be used without curly braces, but choosing not to use them changes the function’s behavior.

The curly braces is called the “block body” syntax and behaves in the same way as a normal function expression in that multiple lines of code can exist inside the arrow function as they would for a normal function expression.

If you remove the curly braces, you are using the “concise body” syntax limited to a single line of code, such as an assignment or expression.

The value of this line will implicitly return.

JavaScript
// βœ… Both are valid
const a = (x) =>  console.log(x);
const b = x => console.log(b);

// Assignment is allowed
let user = {};
const setUserName = (a) => a.name = "John";
setUserName(user);
console.log(user.name); // "John"

// ❌ Invalid syntax:
const sum = (a, b) => return a + b;

Although arrow functions are more readable and easy to use, but cannot be used in some situations. They do not allow arguments, super or new.target, and cannot be used as a constructor. Also, the arrow functions do not have a prototype defined.


Learn More:

Unlock your programming potential with Stack Thrive! Discover step-by-step tutorials, insightful tips, and expert advice that will sharpen your coding skills and broaden your knowledge.

Leave a Comment

Facebook Twitter WhatsApp