The Most Difficult JavaScript Interview Question
Can you answer it?
For of myself I knew that I knew nothing at all …
You think you are decent at JavaScript?
Then let’s see if you know what the following code does…
Here is the headache:
const obj = {
a: 1,
b: function() {
return this.a;
},
c: () => {
return this.a;
}
};
console.log(obj.b()); // Output 1?
console.log(obj.c()); // Output 2?
const test = obj.b;
console.log(test()); // Output 3?
const testArrow = obj.c;
console.log(testArrow()); // Output 4?
Answer:
const obj = {
a: 1,
b: function() {
return this.a;
},
c: () => {
return this.a;
}
};
// Output 1: 1
console.log(obj.b());
// Output 2: undefined
console.log(obj.c());
const test = obj.b;
// Output 3: undefined
console.log(test());
const testArrow = obj.c;
// Output 4: undefined
console.log(testArrow());
Explanation:
obj.b()
:
b
is a regular function, and this
refers to the object obj
when called as obj.b()
. Therefore, this.a
returns 1
.
obj.c()
:
c
is an arrow function, and arrow functions lexically bind this
from their surrounding context. Here, the surrounding context is the global object, and this.a
is undefined
because a
is not a property of the global object.
test()
:
Assigning obj.b
to test
, takes the function b
out of the obj
object. When you call test()
, it's no longer part of obj
. In JavaScript, when you call a function like this, without an object in front of it (just test()
), this
no longer refers to obj
. Instead, it refers to the global object (in browsers, that's window
).
testArrow()
:
Similar to the second case, testArrow
is an arrow function that lexically binds this
from the global scope. Thus, this.a
is still undefined
.
Conclusion
Damn that was a hard question. Did you know about these special behaviors of JavaScript? Let me know in the comments!
Understanding how this
works in JavaScript is really important. Regular functions use this
based on how they are called, meaning the value of this
can change depending on the context. Arrow functions are different because they always keep the this
from the surrounding code where they are defined, regardless of how they are called.
To ensure your functions behave correctly, it’s important to choose between regular and arrow functions based on how you need this
to work in your code.
Happy coding!