Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Arrow Functions

Arrow functions provide a shorter syntax for function expressions.

They are especially useful for callbacks and inline logic.

Why We Need It

Concise code improves readability, and lexical this avoids common bugs in callbacks.

Knowing their limitations helps you choose the right function style.

Syntax

(params) => expression
(params) => { ... }

Basic Example

1. Basic arrow

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

console.log(add(2, 3));

Simple one-line function with implicit return.

Real World Example

2. Single parameter

const square = n => n * n;

console.log(square(5));

Parentheses are optional for a single parameter.

Multiple Use Cases

Concise Syntax

Arrow functions are a shorter syntax for function expressions.

They are great for small callbacks and inline logic.

Lexical this

Arrow functions do not have their own this.

They inherit this from the surrounding scope, which is useful in callbacks.

Implicit Returns

Single-expression arrow functions can return without the return keyword.

Use parentheses when returning an object literal.

More Examples

3. Returning objects

const makeUser = (name) => ({ name });

console.log(makeUser("Ava"));

Wrap object literals in parentheses.

4. Lexical this

const team = {
  name: "Alpha",
  members: ["A", "B"],
  list() {
    return this.members.map((m) => this.name + "-" + m);
  }
};

console.log(team.list());

Arrow functions keep this from the outer scope.

Comparison

Without

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

With

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

Common Mistakes and Fixes

Using arrow as method

Arrow functions should not be used as object methods when you need this.

Forgetting parentheses for object return

Wrap object literals in parentheses.

Overusing arrows

Use regular functions when readability is better.

Interview Questions

What is lexical this?

Arrow functions inherit this from the outer scope.

Can arrow functions be constructors?

No, they do not have a prototype and cannot be used with new.

When should you avoid arrow functions?

When you need a method with its own this value.

Practice Problem

Practice: Convert a function expression into an arrow function.

const multiply = function(a, b) {
  return a * b;
};
// TODO: convert to arrow

One Possible Solution

const multiply = (a, b) => a * b;
console.log(multiply(3, 4));

Frequently Asked Questions

Do arrow functions have their own this?

No, they inherit this from the surrounding scope.

Can arrow functions be used as constructors?

No, they cannot be used with new.

When should I use arrow functions?

For short callbacks and when you want lexical this.

Try It Yourself

Try using arrow functions in different callbacks.