Tip 36: Prevent Context Confusion with Arrow Functions
Explore how to prevent confusion between scope and context by using arrow functions in JavaScript. Understand how arrow functions retain the surrounding 'this' context, helping you avoid common errors when using callbacks like map or setTimeout. This lesson guides you through practical examples to correctly manage function context and lays a foundation for handling 'this' in more complex scenarios.
We'll cover the following...
Scope, context & this keyword
Scope and context are probably the two most confusing concepts for JavaScript
developers. A function’s scope, at it simplest, is what variables the functions
can access. We explored this previously in Tip 3, Isolate Information with Block
Scoped Variables. Now you’re going to learn about context. Context
is what the keyword this refers to in a function or class.
Not only are both concepts hard to grasp, but people often confuse them. I
know I confuse them all the time. Ryan Morr gives a simple way to remember
the difference: Scope pertains to functions and context pertains to objects. While that’s not 100 percent true—you can use this in any function—it’s a good general rule.
Understanding context
To understand context, start with a very simple ...