DEV Community

Cover image for ES6++: 5- Arrow Functions
Hasan Zohdy
Hasan Zohdy

Posted on

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)

Top comments (4)

Collapse
 
frankwisniewski profile image
Frank Wisniewski

check for positive number

let a = 5
console.log(Math.sign(a)) // 1
Enter fullscreen mode Exit fullscreen mode

arrow function for random ??

const randomNumber = Math.random()
Enter fullscreen mode Exit fullscreen mode

Both randomNumber functions return an function not an value

why getPi() Math.PI´s typeof is a Number

When using ES6, use it consequent

const sum = (...args) => 
  args.reduce( (a, b) => a + b, 0 )

console.log(sum(1, 2, 3, 4, 5)); // 15
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hassanzohdy profile image
Hasan Zohdy

The purpose of that example is to getting know what is the replacements for arguments in arrow functions, not about the code written inside the function itself, also the tutorial is mainly for people who are new with ES6 features, that's why i didn't write complex code so everyone can get understand it clearly.

Thanks for your comment and your feedback.

Collapse
 
frankwisniewski profile image
Frank Wisniewski

However, one should not use impractical examples.
and please change to Math.random()

Thread Thread
 
hassanzohdy profile image
Hasan Zohdy

Ah okay, i didn't see that i forgot the parenthesis, thanks for the hint, i updated the post.