JS Interview Qs
JS Interview Qs
------------------------------------------------------------
(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.
The script will stop when the call stack is empty , i.e after executing the
global execution context completely at the end.
------------------------------------------------------------
---------------------------------------------------------------------------------------------------------
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
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
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.
------------------------------------------------------------
(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 = 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.
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.
------------------------------------------------------------
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 -
Example -
Lets take a scenario
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.
---------------------------------------------------------------------------------------------------------
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 -
------------------------------------------------------------
---------------------------------------------------------------------------------------------------------
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
------------------------------------------------------------