Day 5: Amazon and Google Interview Question on SetTimeout

Bhushan Gaikwad
6 min readJun 5, 2021

How come the output of this program is this πŸ‘‡???

πŸ˜€ It's a nice question. Google and Amazon people ask you this question to know your knowledge and grasp on topics like scopes and in general understanding of setTimeout function.To be honest you have all the the knowledge needed to solve this puzzle already. Just remember what you have learned so far from our previous discussions.

Okay, I know about setTimeout, It’s not part of Javascript but part of Web APIs. Browser stores it and runs the timer and bla bla bla..

But what is this scopes?

Aha!! That's why you didn't understood it.Fine!! In this program scope plays important role.In JavaScript, scope refers to the current context of your code. Scopes can be globally or locally defined.Understanding JavaScript scope is key to writing bulletproof code and being a better developer.You’ll understand where variables/functions are accessible, be able to change the scope of your code’s context and be able to write faster and more maintainable code, as well as debug much faster.

😏 hmmmm Okay, It seems useful.

There are different types of scopes in Javascript.- Global Scope
- Local Scope
- Function Scope
- Lexical Scope

😏 Okay, One at a time, What is Global Scope?

In simple words, each variable which is not part of any function is in Global Scope.In the above example on line 1 that 'const arr' is defined in Global Scope.and anywhere within the program it is accessible.

hmmm.. What is Local Scope?

A local scope refers to any scope defined past the global scope. There is typically one global scope, and each function defined has its own (nested) local scope.for example:var five = 5; // part of global scopefunction x() {var ten = 10; // part of local scope}Variable 'five' is in global scope and variable 'ten' is in local scope of function x.Any local scoped items are not visible in the global scope - unless exposed, meaning if I define functions or variables within a new scope, it’s not accessible outside of that current scope. 

πŸ™„ What ????

Let's check this simple example.var myFunction = function () {  var name = 'Todd';   console.log(name); // Todd };// Uncaught ReferenceError: name is not defined 
console.log(name);
`name` is not accessible outside of the function.

🧐 Okay but If this is Local Scope then What is Function Scope?

On the internet, You might find some different information but it's same.All scopes in JavaScript are created with Function Scope only, they aren’t created by `for` or `while` loops or expression statements like `if` or `switch`. New function = new scope // that’s the rule.

hmm.. Okay, πŸ˜’ what is this Lexical Scope? It seems complicated.

πŸ˜‚πŸ˜‚πŸ˜‚πŸ˜‚πŸ˜‚πŸ˜‚πŸ˜‚πŸ˜‚πŸ˜‚Nope it's not.Whenever you see a function within another function, the inner function has access to the scope in the outer function, this is called Lexical Scope or Closure - also referred to as Static Scope. The easiest way to demonstrate is below example:// Scope A 
var myFunction = function () {
// Scope B
var name = 'Todd'; // defined in Scope B
var myOtherFunction = function () {
// Scope C: `name` is accessible here!
};
};It's simple right? πŸ˜‚

πŸ˜… Actually, It is simple. Many people give such horrible names to the simplest concepts. πŸ˜‚πŸ˜‚

Yeah, You are right, unless we know about the thing, It seems so much complicated by names.Okay, So now you know all you need for the given problem.Let's try to run this program!

Okay, Here is the program.

First of all for this Javascript Program new Execution Context is created.

Then in the first phase of Variable environment (Memory Component) all the functions and variables are stored in key value pair.

Then in Thread of Execution (Code Component) Phase each line of code is executed one line at a time.

So on the line 1, It is executed and value of const arr is changed from undefined to [1,2,3,4] this array.

On the next line ie line 3, for loop is initialised and value of i is set to 0 .

On line 5, we have setTimeout , Which calls the Browser Web API and stores this timer into the browser and will wait for 3000 milliseconds (3 seconds).

But as we know already, Javascript waits for nothing and it is a synchronous single threaded language.

So, It goes for second loop, Now at this moment value of i will be incremented to 1 .

Now again no line 5, we have setTimeout , which again calls browser Web API and stores this new timer into the browser and will wait for 3 seconds.

This cycle repeats the same until the value of i is 3.

So on the each loop ie

loop 1 ==> initially i is 0, and new timer is set, and i is incremented to 1

loop 2 ==> initially i is 1, and new timer is set, and i is incremented to 2

loop 3 ==> initially i is 2, and new timer is set, and i is incremented to 3

loop 4 ==> initially i is 3, and new timer is set, and i is incremented to 4

but on the fifth loop,

value of i is 4 and arr.length is also 4, so loop condition i < arr.length fails and loop is stopped.

Now, There is nothing left to be executed, so Global Execution Context is deleted from the call stack.

Hey, but what happened to those timers?

πŸ˜…πŸ€£ 🀣 Yeah, Wait I am coming to that too!!

Now, those 3 seconds are passed, So setTimeout wants to execute those functions, so those functions are passed to callback queues. and once the Call Stack is empty, Event Loop tries to fill it with those callback queue functions and those functions are executed quickly as possible from Call Stack. (If you want to know in detail refer to this post first)

Now because the value of i and arris in Global Scope, It is accessible within the callback of setTimeout.

Now, Interesting part is that callback function is executing after 3 seconds, and before that all the loops are already executed so value of i is now 4 .

So it calls browser web API of `console` and logs Index: 4, Element: undefined , Why undefined because arr[4] is undefined, we have only 4 elements in array and array index starts with 0 so it only has max index 3 .

Yep!! That's absolutely correct.But we have 4 timers in call stack now because that for loop ran 4 times right?so we see the same output 4 times.

Hey, That was easy, The only part I was missing was Scopes.

Yep!! If you understand scopes properly, You can clearly see what is accessible where in the program and thus you write better programs 😎.

Yeah, I understood it now. Previously I was thinking that i will be separate for each callback of the setTimeout and because of that I was imagining completely different output of this program.

So, Today we covered Scopes and you got the answer of very famous interview question asked by AMAZON and GOOGLE. Cheers πŸ₯‚

Yeah, You know what, Once i understood scopes I solved it on my own 🀩 πŸ₯³.

Yes!! πŸ˜‰I am trying my best πŸ˜‡ to make things simple and easy 🀘.So this is how you execute that program.See you tomorrow with another question πŸ‘‹And a humble reminder join me on Twitter, LinkedIn and Github.I share lot of cool tips and tricks regarding PHP, Laravel, Javascript, Vuejs, Nuxtjs, Reactjs, databases, workflows, productivity etc etc.https://twitter.com/rckstrbhushanhttps://www.linkedin.com/in/rckstrbhushanhttps://github.com/bhushanπŸ‘†πŸ»πŸ‘†πŸ»πŸ‘†πŸ»πŸ‘†πŸ»πŸ‘†πŸ»πŸ‘†πŸ»πŸ‘†πŸ»Take care and stay safe. Cheers πŸ₯‚

You too !! Take Care and Stay Safe. Cheers πŸ₯‚

--

--