Skip to main content

Command Palette

Search for a command to run...

Arrow Functions in JavaScript

Updated
3 min readView as Markdown

Introduction

Arrow functions are a modern way to write functions in JavaScript. They were introduced in ES6 (ECMAScript 2015) to make function syntax shorter and easier to read. Arrow functions reduce boilerplate code and improve readability.


1. What are Arrow Functions?

An arrow function is a shorter way of writing a function using the => symbol.

It allows developers to write cleaner and more concise code compared to normal functions.

Example

Normal Function:

function greet(name) {
  return "Hello " + name;
}

Arrow Function:

const greet = (name) => {
  return "Hello " + name;
};

2. Basic Arrow Function Syntax

General syntax:

const functionName = (parameters) => {
   // function body
};

Example:

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

3. Arrow Function with One Parameter

If there is only one parameter, parentheses are optional.

Example:

const square = x => {
  return x * x;
};

Short version:

const square = x => x * x;

4. Arrow Function with Multiple Parameters

If there are two or more parameters, parentheses are required.

Example:

const multiply = (a, b) => {
  return a * b;
};

Short version:

const multiply = (a, b) => a * b;

5. Implicit Return vs Explicit Return

1. Explicit Return

When we use the return keyword and curly brackets {}.

Example:

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

2. Implicit Return

When we remove {} and return. The value is returned automatically.

Example:

const sum = (a, b) => a + b;

Implicit return makes the code shorter and cleaner.


6. Difference Between Arrow Function and Normal Function

Feature Normal Function Arrow Function
Syntax Longer Short and concise
Keyword Uses function keyword Uses => symbol
Code readability More lines Fewer lines
Usage Traditional JS Modern JavaScript

Example comparison:

Normal Function:

function add(a, b) {
  return a + b;
}

Arrow Function:

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

Conclusion

Arrow functions make JavaScript code simpler, shorter, and easier to read. They are widely used in modern JavaScript, especially in callbacks and array methods like map(), filter(), and reduce().