Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

3 cases when you should not use Arrow Functions in Js

I love arrow functions in Javascript! For some reason, they feel much more natural to me, compared with the classic regular Js function expressions.

And also they take fewer keystrokes to type:

//arrow functions
const square = x => x*x
//function expression
const square = function(x) { return x*x }

However, there are cases where arrow functions are not the best option. Let's see some of them.

Do not use arrow functions as actionsListeners

Let's say we want to toggle a CSS class when someone clicks a button. Given that the arrow functions don't have their own context and are automatically bound to the upper context we cannot use easily use them for this scenario:

const button = document.getElementById('the-button')
button.addEventListener('click',  ()=> {
    this.classList.toggle('on')
    // ⛔️ using an arrow function here will result in:
    // Uncaught TypeError: Cannot read properties of undefined
})

With a regular Javascript function things will work as intended:

const button = document.getElementById('the-button')
button.addEventListener('click',  function() {
    this.classList.toggle('on')
    // 👍 a regular function will work as intended
})

Do not use arrow functions as object methods

This one is particularly tricky because it will not throw any error.

Let's take the below object:

const joe = {
  age: 29,
  ages: () => {
    // ⛔️ an arrow function here will actually
    // translates to window.age++
    this.age++;
  },
}

joe.ages()
console.log(joe.age) // 29

The abnormality in the example above happens for the same reason: arrow functions don't have their own context and are automatically bound to the upper context. In this case, the upper context is the window object and not the intended joe object.

Also here a regular function will do the work as intended:

const joe = {
  age: 29,
  ages: function() {
    // 👍 a regular function will work as intended
    this.age++;
  }
}

joe.ages()
console.log(joe.age) // 30

Do not use arrow functions with the call apply or bind methods

We use call, apply or bind methods to set the this keyword independent of how the function is called.

For example:

const numbers = [5, 6, 2, 3, 7];
const max = Math.max.apply({}, numbers);

We cannot use any call, bind, or apply with an arrow function.

Also, keep in mind that the arrows functions don't have access to the arguments object as regular functions do.

And finally, do not use arrow functions when a regular function will be much easier to read.

Home Screencasts Best of Newsletter Search X