Discover how a tiny arrow can save you hours of debugging <code>this</code> confusion!
Why this with arrow functions in Javascript? - Purpose & Use Cases
Imagine you have an object managing a button on a webpage, and you want to change the button's color using a property from your object when it's clicked. You write a function (method) to handle the click, but inside that function, the word this points to the button instead of your object as you expected, making your code confusing and buggy.
Using regular functions for event handlers or callbacks often means this changes its meaning depending on how the function is called. This makes your code slow to write and hard to debug because you have to constantly bind this or use tricks to keep track of it.
Arrow functions keep the this value from the place where they were created. This means you don't have to worry about losing the right this inside callbacks or event handlers. Your code becomes cleaner and easier to understand.
button.addEventListener('click', function() { console.log(this); // 'this' is the button (not your object) });
button.addEventListener('click', () => { console.log(this); // 'this' is from outer scope (your object) });
You can write simpler, more reliable code that keeps the right context without extra work.
When building interactive web pages, arrow functions let you handle user actions without worrying about confusing this changes, making your buttons and forms work smoothly.
Regular functions change this based on how they are called.
Arrow functions keep this from where they are created.
This makes event handling and callbacks easier and less error-prone.
Practice
What is true about this in arrow functions compared to regular functions?
Solution
Step 1: Understand how
Arrow functions do not have their ownthisworks in arrow functionsthis. Instead, they use thethisvalue from the surrounding (lexical) context where they are created.Step 2: Compare with other options
Options B, C, and D are incorrect because arrow functions do not bindthisto the global object, undefined, or themselves.Final Answer:
thisin arrow functions is inherited from the surrounding code where they are created. -> Option AQuick Check:
thisin arrow functions = lexicalthis[OK]
this, not their own [OK]- Thinking arrow functions have their own
this - Confusing arrow functions with regular functions
- Assuming
thisis always global in arrow functions
Which of the following is the correct syntax to define an arrow function that logs this.name?
const obj = { name: 'Alice', logName: ??? }Solution
Step 1: Identify arrow function syntax
Arrow functions use the syntax() => expressionor() => { statements }. logName: () => console.log(this.name) uses the correct concise syntax.Step 2: Check other options
Options B and D use regularfunction()syntax, not arrow functions. logName: () { console.log(this.name) }() { console.log(this.name) }is missing the fat arrow=>, resulting in a syntax error. Note: even with correct arrow syntax as an object method,thiswould refer to the lexical scope (global), not the object.Final Answer:
logName: () => console.log(this.name) -> Option DQuick Check:
Arrow function syntax = logName: () => console.log(this.name) [OK]
- Forgetting the fat arrow '=>'
- Using function keyword instead of arrow syntax
- Confusing arrow function with method shorthand
What will be the output of this code?
const person = {
name: 'Bob',
greet: () => {
console.log(this.name);
}
};
person.greet();Solution
Step 1: Understand
The arrow functionthisin arrow functions inside objectsgreetdoes not have its ownthis. It usesthisfrom the surrounding scope, which is the global scope here.Step 2: Check global
In most environments,this.namethis.namein global scope isundefinedunless explicitly set.Final Answer:
undefined -> Option AQuick Check:
Arrow functionthis= lexicalthis(global) [OK]
this, not object [OK]- Expecting
thisto be the object - Confusing arrow function with regular method
- Assuming global
this.nameis set
Find the error in this code and fix it so that this.name inside greet refers to the user object:
const user = {
name: 'Carol',
greet: () => {
console.log(this.name);
}
};
user.greet();Solution
Step 1: Identify why
Arrow functions do not have their ownthis.nameis incorrectthis, so insidegreet,thisis not theuserobject.Step 2: Fix by using a regular function method
Defininggreetas a regular function method bindsthisto theuserobject when called asuser.greet().Final Answer:
Changegreetto a regular function:greet() { console.log(this.name); }-> Option CQuick Check:
Use regular function for object methods needingthis[OK]
this [OK]- Trying to bind
thisto arrow functions - Using arrow functions for object methods expecting
this - Accessing object properties via global
this
You want to create an object with a method that uses a callback to print the object's name property after 1 second. Which code correctly uses arrow functions to keep this referring to the object?
const obj = {
name: 'Dave',
printName: function() {
setTimeout(??? , 1000);
}
};
obj.printName();Solution
Step 1: Understand
InsidethisinsidesetTimeoutcallbacksetTimeout, a regular function'sthisis global or undefined, so it loses the object context.Step 2: Use arrow function to inherit
Using an arrow function as callback keepsthisfromprintNamethisfromprintName, which is the objectobj.Final Answer:
() => console.log(this.name) -> Option BQuick Check:
Arrow function callback keepsthisfrom method [OK]
this context [OK]- Using regular function losing
thiscontext - Referencing object by name inside callback (less flexible)
- Not using arrow function for callbacks needing
this
Ready to prove it?
Pass the test and this pattern moves unknown
