Facebook Pixel

What are the best practices for the this keyword in JavaScript?

Use regular functions for object methods, arrows for callbacks inside methods, bind in constructor or arrow class fields, always use new, use event.currentTarget for event handlers, enable strict mode, and consider avoiding this when simpler alternatives exist.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in this Keyword Best Practices in JavaScript

Regular functions. Arrow functions inherit this from the enclosing scope, not the object. So obj.greet = () => this.name gives undefined. Use regular functions so this is the object.

Bind in the constructor (this.method = this.method.bind(this)), use arrow class fields (method = () => { ... }), or use arrow wrappers in callbacks (setTimeout(() => this.method(), 1000)). Arrow class fields are the cleanest.

No. Arrow functions do not have their own this. call, apply, and bind cannot change an arrow's this. If you need to set this, use a regular function instead.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.