Tricky JS Interview Questions and Answers
In this article, I will be writing about those questions that made me scratch my head and question my fundamentals of JS and the web in general.
Note: If you’re preparing for an interview, do check out this repo which I frequently update with the latest content frontend-interview-preps
Let’s get started.
- What is the output of the below code?
function Person(name){
this.name = name
}
Person.prototype.getName = function(){
console.log(`The name is ${this.name}`)
}
const ish = new Person('Ish')
setTimeout(ish.getName, 1000)
At the first look of this question, it seems very simple.
Tip: If you’re not familiar with prototype in JavaScript, I suggest you go read this.
When setTimeout(ish.getName, 1000)
gets executed, ish.getName function is registered with the browser’s Web API to be executed after 1000 ms.
After a delay of 1000 ms as soon as the call stack is empty, the function is pushed onto the call stack for execution.
Tip: To understand how the execution of code happens in JS, read this.
And then The name is Ish
should be printed. Which is wrong of course.
Why is this wrong?
Let’s evaluate the same code with a slight change
function Person(name){
this.name = name
}
Person.prototype.getName = function(){
console.log(`The name is ${this.name}`)
}
const ish = new Person('Ish')
// Change here
setTimeout(() => {
ish.getName()
}, 1000)
When the above code is executed The name is Ish
is printed.
Even if you are a JS noob, you know that we did the same thing in both the case with just a slight variation in the syntax. Then why were we wrong in the first case?
Let’s understand what happens when we do setTimeout(ish.getName, 1000)
When we’re passing ish.getName as a first param to the setTimeout
, we’re passing only the reference of the function.
Which is equivalent to :
...
const ishReference = ish.getName
setTimeout(ishReference, 1000)
Now when I write it this way, most of you would have already understood the problem. ishReference
is no more a method of an object, rather it’s just a function having a global scope ofwindow
.
And since we don't have any variable called name
in the global scope, the output we get is The name is undefined
QUIZ
Q1. What would happen if there was a variable var name = ‘Jackey';
in the global scope?
Q2. How can you print The name is Ish
without using arrow functions / passing just the reference?(hint: context binding)
….More content to come soon….
Let me know in the comments if you have any feedback or suggestions.
I hope you found this article useful. I would love to hear your thoughts. 😇
Thanks for reading. 😊
Cheers! 😃
If you find this article useful, you can show your appreciation by clicking on the clap button. As the saying goes, ‘When we give cheerfully and accept gratefully, everyone is blessed’.