Arrow functions in JavaScript (original) (raw)

Last Updated : 17 May, 2025

An arrow function is a shorter syntax for writing functions in JavaScript. Introduced in ES6, arrow functions allow for a more concise and readable code, especially in cases of small functions. Unlike regular functions, arrow functions don't have their own this, but instead, inherit it from the surrounding context.

const add = (a, b) => a + b; console.log(add(5, 3));

`

**1. Arrow Function without Parameters

An arrow function without parameters is defined using empty parentheses (). This is useful when you need a function that doesn’t require any arguments.

JavaScript `

const gfg = () => { console.log( "Hi from GeekforGeeks!" ); }

gfg();

`

Output

Hi from GeekforGeeks!

2. Arrow Function with Single Parameters

If your arrow function has a single parameter, you can omit the parentheses around it.

JavaScript `

const square = x => x*x; console.log(square(4));

`

**3. Arrow Function with Multiple Parameters

Arrow functions with multiple parameters, like ****(param1, param2) => { }**, simplify writing concise function expressions in JavaScript, useful for functions requiring more than one argument.

JavaScript `

const gfg = ( x, y, z ) => { console.log( x + y + z ) }

gfg( 10, 20, 30 );

`

**4. Arrow Function with Default Parameters

Arrow functions support default parameters, allowing predefined values if no argument is passed, making JavaScript function definitions more flexible and concise.

JavaScript `

const gfg = ( x, y, z = 30 ) => { console.log( x + " " + y + " " + z); }

gfg( 10, 20 );

`

5. Return Object Literals

In JavaScript, returning object literals within functions is concise: ****() => ({ key: value })** returns an object { key: value }, useful for immediate object creation and returning.

JavaScript `

const makePerson = (firstName, lastName) => ({first: firstName, last: lastName}); console.log(makePerson("Pankaj", "Bind"));

`

Output

{ first: 'Pankaj', last: 'Bind' }

Async Arrow Functions

Arrow functions can be made asynchronous by adding the async keyword before the parameter list.

const fetchData = async () => {
const data = await fetch('https://api.example.com/data');
return data.json();
};

**Advantages of Arrow Functions

**Limitations of Arrow Functions

Best Practices for Using Arrow Functions

When to Use - Arrow Functions vs. Regular Functions

Aspect Arrow Functions Regular Functions
this Binding Lexically binds this to the surrounding context this is dynamically bound depending on how the function is called
**Syntax Shorter and more concise Requires the function keyword
arguments Object Does not have its own arguments object Has its own arguments object
**Use as Constructor Cannot be used as a constructor Can be used as a constructor with new
**Method Definitions Cannot be used as methods within objects Can be used to define methods in objects
**Return Value Implicit return for single expressions Must use return keyword