ES6++: 5- Arrow Functions

hassanzohdy

Hasan Zohdy

Posted on November 17, 2022

ES6++: 5- Arrow Functions

Arrow Functions

Arrow functions are a new way to write functions in ES6. They are a shorter syntax for writing functions and they do not have their own this and arguments. They also do not have a prototype property.

How to use arrow functions?

To use arrow functions you need to use the => operator instead of the function keyword.

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

// arrow function
const add = (a, b) => {
  return a + b;
};
Enter fullscreen mode Exit fullscreen mode

Actually, we can shorten that even more:

const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

What we did here is that, when we have only a return statement in the function body, we can remove the curly braces and the return keyword and the function will return the value of the expression.

Let's see couple more examples:

// normal function
function isPositive(number) {
  return number >= 0;
}

// arrow function

const isPositive = (number) => number >= 0;
Enter fullscreen mode Exit fullscreen mode
// normal function
function randomString() {
  return Math.random().toString(36).substring(2);
}

// arrow function

const randomString = () => Math.random().toString(36).substring(2);
Enter fullscreen mode Exit fullscreen mode

More Shorter Syntax

If the arrow function has only one parameter you can remove the parentheses:

// normal function

function double(number) {
  return number * 2;
}

// arrow function

const double = (number) => {
  return number * 2;
};

// shorter syntax
const double = (number) => number * 2;

// more shorter syntax
const double = number => number * 2;
Enter fullscreen mode Exit fullscreen mode

No Parameters

If the arrow function has no parameters you need to use empty parentheses:

// normal function

function getPi() {
  return Math.PI;
}

// arrow function

const getPi = () => {
  return Math.PI;
};

// shorter syntax
const getPi = () => Math.PI;
Enter fullscreen mode Exit fullscreen mode

Arrow Functions and this

Arrow functions do not have their own this, which means that the this keyword inside an arrow function will refer to the this keyword in the outer scope.

// normal function
function Person() {
  this.age = 0;

  setTimeout(function growUp() {
    this.age++; // The this refers to the global object, which is window
  }, 1000);
}

let p = new Person();
Enter fullscreen mode Exit fullscreen mode

In the above example, the this keyword inside the growUp function refers to the global object, which is window. To fix this we can use the bind method:

// normal function
function Person() {
  this.age = 0;

  setTimeout(
    function growUp() {
      this.age++; // The this refers to the Person object
    }.bind(this),
    1000
  );
}

let p = new Person();
Enter fullscreen mode Exit fullscreen mode

The bind method returns a new function, where the this keyword is bound to the Person object.

In ES6 we can use arrow functions to solve this problem:

// normal function
function Person() {
  this.age = 0;

  setTimeout(() => {
    this.age++; // The this refers to the Person object
  }, 1000);
}

let p = new Person();
Enter fullscreen mode Exit fullscreen mode

Arrow Functions and arguments

Arrow functions do not have their own arguments object. The arguments object is an array-like object that contains the arguments passed to the function.

// normal function
function sum() {
  let total = 0;
  for (let i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }
  return total;
}

console.log(sum(1, 2, 3, 4, 5)); // 15
Enter fullscreen mode Exit fullscreen mode

In the above example, the arguments object contains the arguments passed to the sum function. We can use the arguments object to loop through the arguments and add them to the total variable.

In ES6 we can use the rest parameter to solve this problem:

// normal function
function sum(...args) {
  let total = 0;
  for (let i = 0; i < args.length; i++) {
    total += args[i];
  }
  return total;
}

console.log(sum(1, 2, 3, 4, 5)); // 15
Enter fullscreen mode Exit fullscreen mode

Arrow Functions and prototype

Arrow functions do not have a prototype property. This means that you cannot use the new keyword with arrow functions.

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

const p = new Person("John"); // TypeError: Person is not a constructor
Enter fullscreen mode Exit fullscreen mode

Best Practices

You'll end up in your real projects using most of the time Arrow functions, they are shorter and easier, also with the help of the rest parameter you can pass as many arguments as you want.

So use Arrow functions if you want to get rid of the this headache and if you want to write shorter functions.

🎨 Conclusion

In this article, we learned about arrow functions in ES6. We learned how to use arrow functions and how they are different from normal functions. We also learned about the this keyword and the arguments object in arrow functions.

☕♨️ Buy me a Coffee ♨️☕

If you like my articles and work, you can buy me a coffee, it will help me to keep going and keep creating more content.

😍 Join our community

Join our community on Discord to get help and support (Node Js 2023 Channel).

📚 Bonus Content 📚

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

Packages & Libraries

React Js Packages

Courses (Articles)

💖 💪 🙅 🚩
hassanzohdy
Hasan Zohdy

Posted on November 17, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

16-ES6++: Reflection In JavaScript
javascript 16-ES6++: Reflection In JavaScript

December 6, 2022

15-ES6++: Proxy In JavaScript
javascript 15-ES6++: Proxy In JavaScript

December 4, 2022

14-ES6++: Null Coalescing in Javascript
javascript 14-ES6++: Null Coalescing in Javascript

November 26, 2022

13-ES6++: Optional Chaining in Javascript
javascript 13-ES6++: Optional Chaining in Javascript

November 26, 2022