JavaScript Arrow Functions and This: A Rule on Style

My purpose here is not to explain the new JavaScript arrow function syntax or how it interacts with the this keyword. Instead, I have made a decision about a best practice that I myself am going to follow and I’m trying to influence others. That said, I feel that I do need to explain the context first.

The JavaScript this keyword confuses the hell out of beginners. In an ordinary function, the this keyword resolves to the context of the function. For example, if the function is a method on an object, then this is that object. This has to do with how the function is invoked. It’s not something internal to the function itself. If the myFunction function refers to this and you invoke it by calling myObj.myFunction() then the this keyword resolves to the myObj object.

JavaScript recently created this new function syntax people refer to as arrow functions. It looks like (arg)=>{expression;}. I guess someone in charge of new standards decided it would somehow make our lives easier if this behaves differently inside an arrow function as compared with regular functions. Yeah, I’m serious. The point of confusion of this is always that nobody knows what the hell it refers to at any point in time, and somebody actually decided to add another situation where the meaning is context-dependent in a confusing and specific way.

So pull out your Master List of Weird Exceptions and add to it that inside an arrow function, the meaning of this is not the context of the arrow function. Instead, this refers to whatever it meant in the scope where the arrow function was defined, lexically. It’s the same as if you defined let self = this on the line before the arrow function was defined and then used self inside the arrow function instead of this.

I like arrow functions because of their brevity. But I think having another weird exception to the usage of this is something we seriously did not need in JavaScript. I therefore suggest the following style rule. There simply will be no this inside arrow functions. The this keyword may not appear inside an arrow function. That is the rule I’m going to enforce in my own code, and I wish others would do the same.

How do you make that work? Well, if you need to refer to the context, then explicitly do the let self = this trick we have been using for years. If that seems tedious, or it seems like it defeats the purpose of using an arrow function in the first place, then take the hint and write a function in the traditional syntax.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s