JavaScript Tutorial

Arrow Functions in JavaScript with Examples

TGTeam GyaniPanditNovember 17, 20264 min read

Hello friends! If you have looked at any modern JavaScript code, you must have seen this little symbol: =>. That is an arrow function. Arrow functions, added in ES6 (2015), are a shorter way to write functions in JavaScript. You will see them everywhere in modern code, especially with array methods like map() and filter(). They are not just shorter, though: they also handle this differently from normal functions, which is the part most beginners miss. So let’s understand both sides, step by step.

Normal Function vs Arrow Function

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

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

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

Output:

5 5

When the body is a single expression, you can drop the curly braces and the return keyword. The value is returned automatically.

That is the basic idea. Now let’s look at the small rules you need to remember while writing them.

Arrow Function Syntax Rules

const square = n => n * n;          // one parameter: brackets optional
const greet = () => "Hello!";       // no parameters: empty brackets needed
const sum = (a, b) => {             // a body with several lines needs { } and return
  const total = a + b;
  return total;
};
console.log(square(4), greet(), sum(5, 6));

Output:

16 Hello! 11

Returning an Object: Wrap It in Brackets

const makeUser = (name, age) => ({ name, age });
console.log(makeUser("Riya", 16));

const broken = (name) => { name: name };
console.log(broken("Riya"));

Output:

{ name: 'Riya', age: 16 }
undefined

In broken, JavaScript reads { } as a function body, not an object, so nothing is returned. Wrapping the object in round brackets fixes it.

So where do arrow functions really shine? With array methods.

Arrow Functions with Array Methods

const marks = [72, 45, 88, 91, 60];
console.log(marks.map(m => m + 5));                 // add 5 grace marks
console.log(marks.filter(m => m >= 60));           // keep 60 and above
console.log(marks.reduce((total, m) => total + m, 0));  // total
console.log([...marks].sort((a, b) => b - a));      // highest first

Output:

[ 77, 50, 93, 96, 65 ]
[ 72, 88, 91, 60 ]
356
[ 91, 88, 72, 60, 45 ]

This is where arrow functions shine: short callbacks that read almost like a sentence.

Friends, up to here arrow functions look like just a shorter way of writing. But now comes the most important part of this lesson.

The Big Difference: this

A normal function gets its own this, decided by how it is called. An arrow function does not have its own this; it uses the this of the code around it. That makes arrow functions perfect for callbacks inside methods:

const timer = {
  seconds: 0,
  startNormal() {
    setTimeout(function () {
      console.log("normal function this.seconds:", this.seconds);
    }, 0);
  },
  startArrow() {
    setTimeout(() => {
      this.seconds += 1;
      console.log("arrow function this.seconds:", this.seconds);
    }, 0);
  },
};
timer.startNormal();
timer.startArrow();

Output:

normal function this.seconds: undefined
arrow function this.seconds: 1

Inside the normal callback, this is no longer timer, so this.seconds is undefined. The arrow callback keeps the this of startArrow(), which is timer.

When NOT to Use Arrow Functions

Because of this behaviour, there are a few places where a normal function is the better choice:

1. As object methods that use this

const counter = {
  count: 5,
  show: () => this.count,      // arrow: this is NOT counter
  showOk() { return this.count; },
};
console.log(counter.show());
console.log(counter.showOk());

Output:

undefined
5

2. As constructors

const Person = (name) => { this.name = name; };
new Person("A");

Output:

TypeError: Person is not a constructor

Use a normal function or a class instead.

3. When you need arguments

Arrow functions have no arguments object. Use rest parameters instead: const count = (...args) => args.length;

Default Parameters Work Too

const hello = (name = "Guest") => `Hello, ${name}`;
console.log(hello(), hello("Aman"));

Output:

Hello, Guest Hello, Aman

So friends, to sum up: arrow functions are not faster than normal functions in any meaningful way, so choose them for readability and for how you need this to behave. If a method uses this, write it with the normal method syntax show() { ... } instead. And if your arrow function returns undefined, check two things: if you used curly braces, you must write return, and if you are returning an object, wrap it in round brackets. Practise with a few array methods and arrow functions will soon feel natural.

Related: JavaScript functions · function expressions · Map keys()

Turn reading into skillsCertificate courses in AI, Data Science and programming.
Explore Courses