Some JavaScript interview questions asked in interviews of product companies

August 04, 2019

In this article, we will be discussing some of the interview questions that were asked in interviews at some of the best companies like Google, Amazon, Uber, etc.




NOTE — Try to solve these questions without seeing the answers.
There is some white space after every question so that you do not directly see the answers and get a chance to solve these questions yourself.


Question 1

Consider the following code snippet and try to identify what will be its output.
.
.
.
.
Have you guessed it ???
.
.
.
Let’s see…

Answer:

The following code will write the value 10 ten times.

The value 10 is printed ten times as the variable i gets hoisted to the top of the code snippet and the final value of i is 10 after the code gets executed.

Question 1 — Part 2

At this point, the interviewer generally asks
“What if I want values from 0-9 in the console?"
Try to guess this before scrolling to the solution…
.
.
.
.
.

Printing values from 0–9 in the console

There are different ways to achieve this…

By using IIFE

IIFE is Immediately Invoked Function Expressions
By using IIFE’s we can also scope the value of the variable i to print the current index instead of printing the final value as 10
Below is the solution to print values 0-9 using IIFE's

Here we wrapped the code of the first loop inside an IIFE that will print the following output in the console.

Using ES6 syntax

There is another way to fix this issue using the ES6 syntax. To print the values from 0-9 in the console, simply replace the var keyword inside the first loop with the let keyword. This way, the variable i does not gets hoisted to the top of the code and its scope gets limited to the loop's block scope.

Output:

Question 2

Let’s look at the following JavaScript code snippet.

Can you identify what could probably go wrong here?
Take some time and try to identify if something could go wrong here
.
.
.
.

Answer

We are playing with references here. After the code gets executed, we will have an array of 5 elements such that each element is referencing the same object.
The final value of arr would look like:

You Might Also Like

0 comments

Follow by Email