Skip to main content

Command Palette

Search for a command to run...

Arrow Functions in JavaScript: A Simpler Way to Write Function

Published
3 min read
Arrow Functions in JavaScript: A Simpler Way to Write Function

Introduced in ES6 (2015), Arrow Functions are a more concise way to write function expressions. They’ve become the industry standard for modern web development because they strip away the "boilerplate" and let you focus on the logic.

Topics which we are going to cover in this blog are as follows

  • What arrow functions are

  • Basic arrow function syntax

  • Arrow functions with one parameter

  • Arrow functions with multiple parameters

  • Implicit return vs explicit return

  • Basic difference between arrow function and normal function


From Normal to Arrow: The Transformation

Let’s see how a standard function expression evolves into an arrow function.

The Traditional Way:

const square = function(n) {
  return n * n;
};

The Arrow Way:

const square = (n) => {
  return n * n;
};

Breaking Down the Syntax

The name comes from the => symbol (the "fat arrow"). Here is how it works depending on your parameters:

  • Zero Parameters: You must use empty parentheses.

    • const sayHi = () => console.log("Hi!");
  • One Parameter: You can actually skip the parentheses!

    • const double = n => n * 2;
  • Multiple Parameters: Parentheses are required.

    • const add = (a, b) => a + b;

Implicit vs. Explicit Return

This is the "magic" of arrow functions.

  • Explicit Return: If you use curly braces { }, you must use the return keyword.

  • Implicit Return: If your function is only one line, you can remove the braces and the return keyword. JavaScript simply "knows" to return that value.

// Explicit (needs return)
const add = (a, b) => { 
  return a + b; 
};

// Implicit (clean and short!)
const addSimple = (a, b) => a + b;

Arrow vs. Normal Functions: What’s the Catch?

While arrow functions are great, they aren't a 100% replacement for normal functions.

  • No this binding: Arrow functions don't have their own this. They inherit it from the code around them. (This is great for some things, but bad for others like object methods).

  • No arguments object: You can't use the arguments keyword inside an arrow function.

  • Not for Constructors: You cannot use new with an arrow function to create an object.


Conclusion

Arrow functions are about readability. By removing the function and return keywords, your code starts to look more like a mathematical formula and less like a wall of text. They are especially powerful when used inside other methods like mapand filter.