Skip to content

Arrow Functions (ES6)

Arrow functions were introduced in ES6. They allow us to write shorter function syntax.

Syntax

let myFunction = (a, b) => a * b;

Comparisons

1. Before ES6 (Traditional)

hello = function() {
  return "Hello World!";
}

2. With Arrow Function

hello = () => {
  return "Hello World!";
}

3. Even Shorter (Implicit Return)

If the function has only one statement, and the statement returns a value, you can remove the brackets {} and the return keyword:

hello = () => "Hello World!";

4. With Parameters

let hello = (val) => "Hello " + val;

this Binding

The biggest difference between Arrow Functions and regular functions is how they handle the this keyword. - Regular Functions: this represents the object that called the function. - Arrow Functions: this represents the object that defined the arrow function (Lexical Scoping).

When NOT to use

Do not use Arrow Functions as methods in objects if you need this to refer to the object itself.