When to not use arrow functions in JavaScript
Arrow functions are a more concise alternative to the traditional function expression but they aren't appropriate everywhere.
Let's check out some examples of times you would not want to use arrow functions.
Scenario 1. Callback functions that require dynamic context.
Callback functions that require dynamic context, such as the element clicked, are not good candidates for arrow functions because you are unable to change the pre-defined context of this
.
jsconst button = document.querySelectorAll( '.cta-button' );button.addEventListener( 'click', () => {this.classList.toggle( 'selected' ); // `this`refers to the Window. âšī¸} );
Using a regular function allows the value of this
to change based on the context of the target element.
jsconst button = document.querySelectorAll( '.cta-button' );button.addEventListener( 'click', function() {this.classList.toggle( 'selected' ); // `this`refers to the button! đđđ} );
arguments
object.
Scenario 2. Functions that use the Arrow functions do not bind the global arguments
object.
jsconst logUser = () => {console.log(arguments[0]); // Uncaught ReferenceError: arguments is not defined đ}logUser( 'Kevin' );
But with a regular function, you have access to the global arguments
object.
jsfunction logUser() {console.log(arguments[0]); // Kevinconsole.log(arguments[1]); // Langley}logUser( 'Kevin', 'Langley' );
Scenario 3. Prototype Methods
jsfunction User(firstName, lastName) {this.name = `${firstName} ${lastName}`;}User.prototype.sayHello = () => {return `Hello, ${this.name}`;}const me = new User( 'Kevin', 'Langley' );me.sayHello(); // Hello,
The this
value in the sayHello
method references the global object and not the User
object that it is trying to access.
Instead, write your prototype methods the old fashioned way.
jsfunction User(firstName, lastName) {this.name = `${firstName} ${lastName}`;}User.prototype.sayHello = function() {return `Hello, ${this.name}`;}const me = new User( 'Kevin', 'Langley' );me.sayHello(); // Hello, Kevin Langley
Scenario 4. Object methods
jsconst user = {name: 'Kevin Langley',sayHello: () => `Hello, ${this.name}`;}user.sayHello(); // Hello,
The this
value in the sayHello
method references the global object and not the User
object that it is trying to access.
Instead, write your prototype methods the old fashioned way.
jsconst user = {name: 'Kevin Langley',sayHello() {return `Hello, ${this.name}`;}}user.sayHello(); // Hello, Kevin Langley
Last updated: