0
0
Javascriptprogramming~15 mins

this with arrow functions in Javascript - Deep Dive

Choose your learning style9 modes available
Overview - this with arrow functions
What is it?
In JavaScript, the keyword 'this' refers to the object that is currently executing the code. Arrow functions are a special kind of function that do not have their own 'this'. Instead, they use the 'this' value from the place where they were created. This makes arrow functions behave differently from regular functions when it comes to 'this'.
Why it matters
Understanding how 'this' works with arrow functions helps avoid bugs and confusion in your code. Without this knowledge, you might write functions that don't behave as expected, especially when using callbacks or methods inside objects. This can lead to errors that are hard to find and fix.
Where it fits
Before learning this, you should know how regular functions and the 'this' keyword work in JavaScript. After this, you can learn about advanced function concepts like closures, classes, and event handling where 'this' plays a big role.
Mental Model
Core Idea
'this' in arrow functions always points to the surrounding context where the arrow function was created, not where it is called.
Think of it like...
Imagine 'this' as a sticky note attached to a desk. Regular functions get a new sticky note each time they are called, showing who is using them. Arrow functions don’t get a new sticky note; they keep the one from the desk where they were made.
Context (Surrounding function or global scope)
  └─ Arrow Function (inherits 'this' from context)

Regular Function Call
  └─ Own 'this' based on how called

Flow:
[Context] ──> [Arrow Function uses same 'this']
[Call Site] ──> [Regular Function gets new 'this']
Build-Up - 7 Steps
1
FoundationUnderstanding 'this' in regular functions
🤔
Concept: 'this' refers to the object that calls the function, which can change depending on how the function is called.
function show() { console.log(this); } const obj = { show }; show(); // 'this' is global or undefined in strict mode obj.show(); // 'this' is obj const detached = obj.show; detached(); // 'this' is global or undefined
Result
The output changes: first call logs global object, second logs obj, third logs global again.
Knowing that 'this' depends on the call site helps understand why functions behave differently when called in different ways.
2
FoundationArrow functions do not have their own 'this'
🤔
Concept: Arrow functions inherit 'this' from the surrounding code where they are created, ignoring how they are called.
const obj = { arrow: () => { console.log(this); }, regular() { console.log(this); } }; obj.arrow(); // 'this' is not obj obj.regular(); // 'this' is obj
Result
obj.arrow() logs the global or outer 'this', obj.regular() logs obj.
Understanding that arrow functions don't get their own 'this' explains why they behave differently inside objects.
3
IntermediateUsing arrow functions to fix 'this' in callbacks
🤔Before reading on: do you think arrow functions change the 'this' inside callbacks or just keep it the same? Commit to your answer.
Concept: Arrow functions keep the 'this' from the outer function, which helps avoid losing 'this' in callbacks.
function Timer() { this.seconds = 0; setInterval(() => { this.seconds++; console.log(this.seconds); }, 1000); } new Timer();
Result
The timer counts seconds correctly because 'this' inside the arrow function is the Timer object.
Knowing arrow functions inherit 'this' prevents common bugs where callbacks lose their intended context.
4
IntermediateArrow functions cannot be used as constructors
🤔Before reading on: do you think arrow functions can be used with 'new' to create objects? Commit to your answer.
Concept: Arrow functions do not have a 'prototype' property and cannot be used with 'new' to create instances.
const Person = (name) => { this.name = name; }; const p = new Person('Alice'); // TypeError: Person is not a constructor
Result
Trying to use 'new' with an arrow function causes an error.
Understanding this limitation helps avoid runtime errors and clarifies when to use regular functions.
5
IntermediateArrow functions and 'arguments' object
🤔Before reading on: do you think arrow functions have their own 'arguments' object? Commit to your answer.
Concept: Arrow functions do not have their own 'arguments' object; they use the one from the outer function.
function outer() { const arrow = () => { console.log(arguments); }; arrow(3, 4); } outer(1, 2);
Result
Logs [1, 2], the arguments of outer, not the arrow function call.
Knowing arrow functions share 'arguments' helps avoid confusion when handling parameters.
6
AdvancedArrow functions in class methods and event handlers
🤔Before reading on: do arrow functions inside classes bind 'this' automatically or do you need to bind them manually? Commit to your answer.
Concept: Arrow functions inside classes inherit 'this' from the class instance, avoiding the need to bind manually in event handlers.
class Button { constructor() { this.count = 0; this.handleClick = () => { this.count++; console.log(this.count); }; } } const btn = new Button(); const click = btn.handleClick; click(); // 1
Result
The count increments correctly because 'this' is bound to the Button instance.
Understanding this pattern simplifies event handling and avoids common binding mistakes.
7
ExpertSurprising 'this' behavior with nested arrow functions
🤔Before reading on: do nested arrow functions each have their own 'this' or share the same 'this'? Commit to your answer.
Concept: Nested arrow functions all share the same 'this' from the nearest non-arrow function or global scope.
const obj = { method() { const arrow1 = () => { const arrow2 = () => { console.log(this); }; arrow2(); }; arrow1(); } }; obj.method();
Result
Logs obj because 'this' is inherited from method, the nearest regular function.
Knowing that arrow functions share 'this' through nesting helps predict behavior in complex code.
Under the Hood
Arrow functions do not create their own 'this' binding. Instead, when an arrow function is created, it captures the 'this' value from its surrounding lexical environment. This means that inside the arrow function, 'this' is fixed and does not change based on how the function is called. The JavaScript engine stores this captured 'this' internally and uses it whenever the arrow function runs.
Why designed this way?
Arrow functions were introduced to simplify common patterns where developers had to manually bind 'this' or use workarounds like 'var self = this'. By capturing 'this' lexically, arrow functions reduce boilerplate and bugs related to context loss. The design trades off flexibility (no own 'this') for simplicity and predictability in many use cases.
┌─────────────────────────────┐
│ Surrounding Context (e.g., function or global) │
│  this = X                  │
└─────────────┬───────────────┘
              │
              ▼
    ┌───────────────────┐
    │ Arrow Function    │
    │ Uses this = X     │
    └───────────────────┘

Regular Function Call:
    ┌───────────────────┐
    │ Regular Function  │
    │ this depends on   │
    │ call site         │
    └───────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do arrow functions have their own 'this' that changes with how they are called? Commit yes or no.
Common Belief:Arrow functions have their own 'this' just like regular functions.
Tap to reveal reality
Reality:Arrow functions do not have their own 'this'; they always use the 'this' from where they were created.
Why it matters:Believing this causes bugs where arrow functions behave unexpectedly, especially when used as methods.
Quick: Can arrow functions be used as constructors with 'new'? Commit yes or no.
Common Belief:Arrow functions can be used with 'new' to create objects like regular functions.
Tap to reveal reality
Reality:Arrow functions cannot be used as constructors and will throw an error if called with 'new'.
Why it matters:Trying to use 'new' with arrow functions causes runtime errors and crashes.
Quick: Do arrow functions have their own 'arguments' object? Commit yes or no.
Common Belief:Arrow functions have their own 'arguments' object representing their parameters.
Tap to reveal reality
Reality:Arrow functions do not have their own 'arguments'; they use the 'arguments' from the outer function.
Why it matters:Misusing 'arguments' in arrow functions leads to unexpected values and bugs.
Quick: Does 'this' inside an arrow function inside a method always refer to the object? Commit yes or no.
Common Belief:'this' inside an arrow function method always refers to the object owning the method.
Tap to reveal reality
Reality:'this' inside an arrow function refers to the outer context, which may not be the object if the method is called differently.
Why it matters:Assuming 'this' is the object can cause subtle bugs when arrow functions are used as methods.
Expert Zone
1
Arrow functions capture 'this' at creation time, which means if you create an arrow function inside a regular function, it inherits that function's 'this', not the global or object context.
2
Using arrow functions as object methods can be dangerous because they do not have their own 'this', so 'this' might not refer to the object as expected.
3
Arrow functions do not have a 'prototype' property, so they cannot be used with 'new' or for inheritance, which affects design choices in class-like structures.
When NOT to use
Avoid arrow functions when you need a function to have its own dynamic 'this', such as object methods that rely on 'this' to refer to the object, or when you need to use the function as a constructor. Use regular functions in these cases.
Production Patterns
In production, arrow functions are commonly used for callbacks, especially in event handlers and promises, to maintain the outer 'this' context. They are also used in class fields to define methods that automatically bind 'this', reducing the need for manual binding.
Connections
Lexical Scoping
Arrow functions inherit 'this' lexically, similar to how variables are looked up in lexical scope.
Understanding lexical scoping helps grasp why arrow functions capture 'this' from their creation context, making 'this' behave like a normal variable.
Closures
Arrow functions create closures that include the 'this' value from their surrounding scope.
Knowing closures explains how arrow functions remember the 'this' value even when called later or asynchronously.
Object-Oriented Programming (OOP)
Arrow functions affect how methods behave in objects and classes by changing 'this' binding rules.
Understanding 'this' with arrow functions clarifies method binding and inheritance patterns in OOP.
Common Pitfalls
#1Using arrow functions as object methods expecting 'this' to refer to the object.
Wrong approach:const obj = { value: 10, getValue: () => this.value }; console.log(obj.getValue()); // undefined or global value
Correct approach:const obj = { value: 10, getValue() { return this.value; } }; console.log(obj.getValue()); // 10
Root cause:Arrow functions do not have their own 'this', so 'this' refers to the outer context, not the object.
#2Trying to use 'new' with an arrow function to create an object.
Wrong approach:const Person = (name) => { this.name = name; }; const p = new Person('Alice'); // Error
Correct approach:function Person(name) { this.name = name; } const p = new Person('Alice'); // Works
Root cause:Arrow functions lack a 'prototype' and cannot be used as constructors.
#3Expecting 'arguments' inside an arrow function to refer to its own parameters.
Wrong approach:function outer() { const arrow = () => { console.log(arguments); }; arrow(1, 2); } outer(3, 4); // logs [3,4], not [1,2]
Correct approach:function outer() { const regular = function() { console.log(arguments); }; regular(1, 2); // logs [1,2] } outer(3, 4);
Root cause:Arrow functions do not have their own 'arguments' object; they use the outer function's.
Key Takeaways
Arrow functions do not have their own 'this'; they use the 'this' from where they were created.
This behavior makes arrow functions ideal for callbacks where you want to keep the surrounding context.
Arrow functions cannot be used as constructors and do not have a 'prototype'.
Using arrow functions as object methods can cause unexpected 'this' values and should be avoided.
Understanding how arrow functions handle 'this' helps write clearer, bug-free JavaScript code.