0% found this document useful (0 votes)
20 views

JS Interview Qs

Uploaded by

Bhavesh Damor
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

JS Interview Qs

Uploaded by

Bhavesh Damor
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 30

JavaScript

1) What is execution context & How JS works


(i) Execution Context or Global Execution Context - The environment in
which your code is running .It is created when your code is executed.

Everything in JS happens inside an execution context.


------------------------------------------------------------
(ii) Execution context has two components - Memory & Code
In Memory component, all the variables & functions are stored as key-value
pairs.It is also knows as variable environment.
In Code component , js code is executed one at a time.It is also k/a thread of
execution.

------------------------------------------------------------
(iii) JS is a single threaded synchronous language , it means that it has only
one call stack and can only run one command at a time.Also it executes
commands in an order meaning it is synchronous i.e it can only go to the next
line when the current line is being executed.
---------------------------------------------------------------------------------------------------------
2)How a JS code is executed?
(i) When we run/execute a JS code , first a (global) execution context is created.
------------------------------------------------------------
(ii) JS performs/creates two phases while executing a code -
Memory Creation Phase & Code Execution Phase
I - Memory Creation Phase - In this phase , all the variables & funcs are
allocated memory in memory heap.
When a var is allocated with memory , it’s initial value is set to ‘undefined’.
When a func is allocated with memory , it’s initial value is set to the content
present in itself i.e the code present in it.

II - Code Execution Phase


After the memory allocation , code execution phase runs and JS executes the
code line by line (synchronous) and assigns the values to variables.
X will be assigned with 10

For each func call , a new function execution context is created.


Now again Memory Creation Phase will run for thath func execution context.It
is similar to global execution context but instead of again creating a global
object , it will create an argument object referencing to all the parameters
passed to out func.Sets ‘this’ value to the global object, and initializes
the a parameter to undefined
During the code execution phase of the function execution context, the
JavaScript engine executes each line & assigns 10 to the parameter a and
returns the result (100) to the global execution context:
Now when the JS encounters return stmnt inside the function , it will return the
control of the program back to the place where the func was called and in our
case it was called in the global execution context.
---------------------------------------------------------------------------------------------------------
3)Call Stack
In Code Execution Phase , JS uses a call stack to manage execution contexts -
global EC & func EC

When you execute a script, the JavaScript engine creates a Global


Execution Context and pushes it on top of the call stack.

Whenever a function is called, the JavaScript engine creates a function


execution context for the function, pushes it on top of the call stack, will
run memory creation phase for it’s vars or funcs & starts code execution
phase for executing code

If a function calls another function, the JavaScript engine creates a new


function execution context for the function that is being called and pushes
it on top of the call stack.

When the current function completes or a return stmnt is executed, the


JavaScript engine pops it off the call stack and resumes the execution
where it left off i.e passing the control of the program back to where the
func was called.

The script will stop when the call stack is empty , i.e after executing the
global execution context completely at the end.
------------------------------------------------------------

Call stack maintains the order of execution of execution contexts.

It is also k/a execution context stack , program stack ,control stack ,


runtime stack , machine stack.

---------------------------------------------------------------------------------------------------------
4)JS Hoisting
During the memory creation phase in global execution context , the variables &
funcs declarations are moved to the top of our code.We can run funcs or access
vars even before they are initialized.
(i) Variable hoisting
During the creation phase of the global execution context, the JavaScript
engine places the variable counter in the memory and initializes its value
to undefined
Variable hoisting works for var ,let & const but it will give referenceError for let
& const
------------------------------------------------------------
(ii)Function hoisting

o/p - result = 30
In this example, we called the add() function before defining it. The above code
is equivalent to the following:

Remember in code execution phase , an argument object gets created for func
execution context and that way a & b gets initialize resulting in 30.

Func hoisting only works for function declaration , for function expressions &
arrow function it will initialized that var with undefined.
Since var becomes undefined , hence we face an error saying that variable is
not a function

---------------------------------------------------------------------------------------------------------
5)window object & this keyword
Window is a global object which gets created along with the global execution
context.And then ‘this’ object is binded to the window object

Window is created in browsers and global is created in nodejs.Also ,


this === window is true
------------------------------------------------------------
Whenever we create a variable or function in global scope , they get attached
to the window global object -
Var a & func b are present in global window object.
Var x wont be present in the window object as it is defined in the func and as
we know func has their own scope because they have their own execution
context.
------------------------------------------------------------

So if we don’t put ‘window’ or ‘this’ before a variable , JS assumes that it is


present in the global scope.
---------------------------------------------------------------------------------------------------------

6)Scope , lexical environment, scope chain


(i) Scope - It determines where a specific stmnt can be accessed in our code.
Three types - global scope, function scope & block scope
------------------------------------------------------------
(ii) Lexical environment -

So lexical env of func c() = local memory of func c() + lexical env of its parent i.e
func a()
------------------------------------------------------------
(iii) Scope chain - Whenever our code tries to access a variable during the
function call, it starts the searching from local variables. And if the variable is
not found, it'll continue searching in its outer scope or parent functions' scope
until it reaches the global scope and completes searching for the variable there.
Chain of lexical environment is called scope chain.
---------------------------------------------------------------------------------------------------------
7)undefined vs not defined in JS
Undefined - It is assigned to a variable until that variable is initialized with a
value. It is like a placeholder.var is taking some memory space & is present in
execution context.
Not defined - var is not taking any memory i.e. not declared.
---------------------------------------------------------------------------------------------------------
8)JS is a loosely/weakly typed language
JavaScript is a loosely typed language, meaning you don't have to specify what
type of information will be stored in a variable in advance
Meaning a var can store numbers , string , bool , etc , unlike strongly typed
languages like C , C++ , we can only store integers in int , strings in string ,
Booleans in bool , etc

------------------------------------------------------------

---------------------------------------------------------------------------------------------------------
9)Temporal dead zone
console.log(aVar); // undefined
console.log(aLet); //ReferenceError: Cannot access 'aLet' before initialization
var aVar = 1;
let aLet = 2;
console.log(aLet); // 2

Accessing a var before it is declared has the result undefined; accessing


a let or const before it is declared throws ReferenceError

let and const are hoisted (like var, class and function), but there is the phase
between the starting of the execution of block in which the let or const is
declared till that variable is being initialized is called Temporal Dead Zone for
the let const variable.

And when we cant access the let & const in this TDZ period , if we did we will
get the reference error shown above.
---------------------------------------------------------------------------------------------------------
10)Block , Block scope , lexical scope, shadowing
(i) Block - A block is basically any code encapsulated inside the curly braces.
Now why we use a block? Block is also k/a compound statement, it is used to
combine multiple JS stmnts into one group.
But why we need a block? We need block at a place where JS expects only one
stmnt.
Example -
If(cond) console.log(a)
An if stmnt can only have a single stmnt after it checks the condition. So to
have multiple stmnts for a condition we need to use a block wrapping all the JS
code.
If(cond) {
console.log(a)
console.log(b)
}
------------------------------------------------------------
(ii) Block scope - Variables and funcs we can access inside a block.Mainly let
and const are block scoped variables.

b & c are hoisted in a separate memory space whereas a is hoisted in global


scope.
That’s why let & const are only accessible in the block and var can be accessed
anywhere in the global scope.
Because JS didn’t found ‘b’ in global scope

------------------------------------------------------------
(iii) Shadowing -
In case of var , when two variables of same name is defined , one variable
shadows the other one and we may have the value from the one who shadows.

Var a of block scope o/ps 10 , var a = 100 gets shadowed by var a = 10


What if we console.log(a) outside of block scope -

Var a = 100 was already shadowed and var a = 10 also modified the value of a,
resulting 10 even outside the block. This happens because, var a =100 & var a
=10 both the cases are defined in global object. And var a = 10 modifies the var
a = 100 which was defined first .So we got 10.
In case of both let & const -
Because of block scope , we are able to see different values
---------------------------------------------------------------------------------------------------------
11)To print array elements every sec
Var arr = [1,2,3,4,5]
Using setInterval & clearInterval -

------------------------------------------------------------
Using setTimeout
Before the actual solution , we have to address the issue using this method.If
we do something like this -

As setTimeout is an async method , JS wont wait for it and the loop will quickly
compute i to it’s limit i.e 6.Here setTimeout takes a callback function and for
every second , the same i value gets printed.
In a closure property , the inner function always has the reference value of the
outside variable , in our case the inner call back func has access to the
reference to the i of the loop and because every callback func for diff time are
pointing to the same reference i , they all prints the same I value i.e 6
Note we are printing i instead of arr[i] to get a better understanding , arr[i] i.e
arr[6] will print undefined 5 times.
So to print different I values and diff array elements we have to pass different
i values to setTimeout callback function , there are two ways to solve this -
1)using let

As let has a block scope , so every callback function for different time 1000*i
will receive diff i values , resulting in our solution
2)wrapping setTimeout inside a function
By not using let, we need to wrap setTimeout inside a function and passing the
i value to it.This runs because function have their own scope for every 1000*i,
so i values will always be different and we will have our desired result.

Now using let & function , we just gave them a different scope so that i is
different every time. Now we can print diff array elements every second
---------------------------------------------------------------------------------------------------------
12)Functions
(i) function statement aka function declaration
function demo(){
console.log('hello')
}
demo()
------------------------------------------------------------
(ii) Anonymous function
func without a name.Will throw syntax error
function (){
console.log('hello');
}
------------------------------------------------------------
(iii)Function expression
Anonymous func assigned to a var
var x = function (){
console.log('hello');
}
x()
------------------------------------------------------------
(iv)Named function expression
func stmnt/declaration assigned to a var
var x = function demo(){
console.log('hello');}
x() //will run the func
demo() //will show a referenceError saying demo is not defined because
//'demo func' is not defined in global scope instead 'x' is defined
//for that func.Hence the error says demo is not defined
------------------------------------------------------------
(v)arrow function
It is a compact alternative to a traditional func expr
var x = () => console.log('hello');
------------------------------------------------------------
(vi)First class funcs or why funcs are called first class citizens?
Because they can be assigned to a variable , can be passed as an argument and
can be returned inside another function.Funcs in JS have the ability to be used
like values.
---------------------------------------------------------------------------------------------------------
13)Callback func in JS
A func which gets passed to an another func is called a callback func.

‘later’ is a callback func and it’s ‘demo’s responsibility to execute/perform


‘later’ inside it.call back funcs are used in a scenario where we want to
perform a functionality(call back func) only after a particular functionality
Example of call back funcs -
setTimeout or setInterval takes a callback func , which gets executed after the
timer.’next’ in expressJS is also a callback func
---------------------------------------------------------------------------------------------------------
14)Event loop
JS Runtime Environment contains JS engine , Web APIs , event loop , callback
queue , microtask queue.Chrome has V8 JS engine.NodeJS is an opensource
JS runtime environment and it also uses the same V8 JS engine
(i) How does JS handle asynchronous tasks?
Functions or operations running parallel with the other functions or
operations are called asynchronous functions or operations in JavaScript.
Asynchronous JavaScript code requires Callback functions that get executed
later after the desired time.

JS engine consist of a call stack and memory heap.

When a setTimeout operation(callback func) is processed in the


stack, it is sent to the Browser’s Web API environment where it
waits for the timer to expire.

Once the timer expires , the operation which was present in the
setTimeout gets sent to the event queue.

Now the event loop constantly checks whether or not the call
stack is empty. If it is empty, that operations are added from the
event queue.
------------------------------------------------------------

(ii) What is microtask queue

Microtask Queue is like the Callback Queue, but Microtask Queue has higher
priority. All the callback functions coming through Promises and Mutation
Observer will go inside the Microtask Queue. For example, in the case
of .fetch (), the callback function gets to the Microtask Queue. Promise
handling always has higher priority so the JavaScript engine executes all the
tasks from Microtask Queue and then moves to the Callback Queue.

---------------------------------------------------------------------------------------------------------
15)Implicit & explicit Binding
Line 14 - we are calling ‘display’ of obj1 by using explicit binding using ‘call’.
‘this’ keyword now points to obj2.
------------------------------------------------------------
Now what if we change the anonymous function to an arrow function?

o/p -

Line 5 - ‘this’ keyword in an arrow function points to the window/global object.


Arrow functions do not bind their own this, instead, they inherit the one
from the parent scope, which is called "lexical scoping".
---------------------------------------------------------------------------------------------------------
16)Implement Caching/Memoize function
What is memoization?
Memoization is an optimization technique that speeds up
applications by storing the results of expensive function calls and
returning the cached result when the same inputs are supplied
again.

What is an expensive function call?


In the context of computer programs, the two major resources we have
are time and memory. Thus, an expensive function call is a function call
that consumes huge chunks of these two resources during execution due
to heavy computation.

Example -
Lets take a scenario

We have an expensive function.


o/p -

As we can see the second call took more time than the first call.So imagine if
we have to make the same call multiple number of times.
------------------------------------------------------------
The idea behind memoization is that we will store/cache the output for the first
calculation with the parameters in a memorization func.
Now for the second call , we will put a condition & check whether the same
parameters are being passed or not.If they are , we will simply return the
already cached value else we will compute with the new arguments the func
received and return it.

Line 1 - our memorize function , which will be a HOF


Line 2 - result object will store our cached values
Line 4 - will return another function which will take the arguments as an array
Line 5 - will convert the arguments into a string because -
result={
“10,20” : 200,
“4,8” : 32,
…}
So every argument will have their values cached/stored inside the result object
and we can alter them using result[“10,20”] = 200 , just like we do in onChange
for a user object if it have multiple fields - [e.target.name] : e.target.value
we suggest simply using JSON.stringify to create a hash of
the arguments passed to our function.
Line 7 - if the arguments are not present in result object , that means they are
new and we will send them to the original func to get the value and will store it
inside result object
Line 11 - will simply return the result for those arguments
Line 23,24 - outer func will take the expensive function and inner func will take
the arguments for it
o/p -

---------------------------------------------------------------------------------------------------------
17) What is the o/p

---------------------------------------------------------------------------------------------------------
16)Infinite Currying
What if the func call is like add(1)(2)(3)(4)(5)(6)……
How will you create the function for this?
Answer -

Line 3 - we will check if next parameter is present or not.If present then we


will return the addition of parameter till that point back to add() , else we will
return the addition of all parameters till that point
Do a dry run and you will understand how it works.For the last empty
parameter , it will see that it is not present and then will return the param1
i.e the sum of all the params until now.
o/p - 21
Note - do provide an empty parenthesis at the end to run the func else we
will get the function code as console.log
---------------------------------------------------------------------------------------------------------
16)Implement this code

------------------------------------------------------------
---------------------------------------------------------------------------------------------------------
17)Remove duplicate values from JS
Method 1 - using set() from ES6

------------------------------------------------------------
Method 2 - using filter method

Explanation -
o/p -

---------------------------------------------------------------------------------------------------------
18)

---------------------------------------------------------------------------------------------------------
19)what is the output of console.log(0.1+0.2)?

https://dev.to/pankajtanwarbanna/do-you-know-0-1-0-2-0-3-in-javascript-
here-is-why-2mea
in JS every number is converted into a binary representation even the float
numbers but every possible real number can’t be converted to binary. As we
can see, there is no exact binary representation possible for 0.3 so JavaScript
interprets 0.3 as the closest possible binary number in decimal.
If we try to log the result of 0.1 + 0.2,
0.3000000000000000444089209850062616169452667236328125
So, JavaScript logs out the minimum number of digits to uniquely identify that
number which is -
0.30000000000000004
More examples -

---------------------------------------------------------------------------------------------------------
20)What is a promise?
A promise is an object that may produce a single value some time in the future:
either a resolved value, or a reason that it’s not resolved (e.g., a network error
occurred). A promise may be in one of 3 possible states: fulfilled, rejected, or
pending.
------------------------------------------------------------
A promise is an object which can be returned synchronously from an
asynchronous function. It will be in one of 3 possible states:
 Fulfilled: onFulfilled() will be called (e.g., resolve() was called)
 Rejected: onRejected() will be called (e.g., reject() was called)
 Pending: not yet fulfilled or rejected
A promise is settled if it’s not pending (it has been resolved or rejected).
Sometimes people use resolved and settled to mean the same thing: not
pending.
------------------------------------------------------------
The then() method in JavaScript has been defined in the Promise API and is
used to deal with asynchronous tasks such as an API call. ‘then()’ method can
either return a Promise or nothing.
------------------------------------------------------------
The catch() handle error handling in case of a promise rejection.
As you can see, the .catch doesn’t have to be immediate. It may appear after
one or maybe several ‘then()’.The easiest way to catch all errors is to
append catch() to the end of then() chain
---------------------------------------------------------------------------------------------------------
21)Polyfill in JS
A polyfill is a piece of code (usually JavaScript on the Web) used to provide
modern functionality on older browsers that do not natively support it. ... The
polyfill uses non-standard features in a certain browser to give JavaScript a
standards-compliant way to access the feature
Polyfills allow web developers to use an API regardless of whether or not it is
supported by a browser, and usually with minimal overhead. Typically they first
check if a browser supports an API, and use it if available, otherwise using their
own implementation.
First, we have to do the feature detection to see if the filter method is already
supported. In this case, we just need to check if there is a function in the Array
prototype named filter . If not, we can create it. And now we can write the
implementation
https://javascript.plainenglish.io/how-to-create-a-polyfill-3c924fa11417
map & bind polyfills - https://akashjain993.medium.com/js-polyfills-interview-
questions-cb431f3c98dd
bind & reduce polyfills - https://dev.to/shibinlal/two-major-polyfill-interview-
question-s-every-js-developer-face-5d7o
---------------------------------------------------------------------------------------------------------
22)MultiQos JS interview coding questions
------------------------------------------------------------

You might also like