JavaScript Interview Questions
JavaScript Interview Questions
What is Hoisting?
• Hoisting is default behavior in JS, where all the variable (Only var) and function declarations
are moved up. It takes place in local and global scope.
x=1;
console.log(x); // Returns 1
var x;
• In order to avoid that, we can “use strict” mode to avoid this.
STRING COERCION
var x = 3;
var y = "3";
var Z = "Hello";
x + y // Returns "33"
x + z // Returns “3Hello”
• Type coercion occurs while using “–“ operator too.
var x = 3;
Var y = "3";
x - y //Returns 0 since the variable y (string type) is converted to a number type
BOOLEAN COERCION
• Boolean coercion takes place when using logical operators, ternary operators, if statements
and loop checks.
• Falsy values are false, 0, 0n, -0,””, undefined, NaN
EQUALITY COERCION
“==” Checks the value but not the type. There is a chance type coercion to occur at one operand.
var a = 12;
var b = "12";
a == b // Returns true because both 'a' and 'b' are converted to the same type and then compared
. Hence the operands are equal.
• “===” Check for both value and type. No type coercion takes place.
var a = 226;
var b = "226";
a === b // Returns false because coercion does not take place and the operands are of different ty
pes. Hence, they are not equal.
• Unlike other programming languages, Logical AND (&&) and Logical OR (||) returns the one
of the operands not Boolean value
• In OR operator, If the first operand is truthy, then first value is returned. Similarly, if the first
value is falsy. It always returns second operand value.
• In AND operator, if all the values of operands are truthy, then it returns last operand value. If
first operand is falsy then first operand is returned. Similarly, second operand is falsy, then
second operand is returned.
var x = 220;
var y = "Hello";
var z = undefined;
x | | y // Returns 220 since the first value is truthy
if( x && y ){
console.log("Code runs" ); // This block runs because x && y returns "Hello" (Truthy)
}
if( x || z ){
console.log("Code runs"); // This block runs because x || y returns 220(Truthy)
}
What is NaN?
• NaN stands for Not a Number. Type of NaN is Number. It represents value is not valid/legal
number
• isNaN() function is used check whether the provided value is valid/legal number by
converting them to number and then equates to NaN.
Example
• Pass by value only happens in Primitive data types like string, number, bigint, boolean,
symbol.
Example:
var y = 234;
var z = y;
• In example, Y is assigned with a value 234, the “=” operator allocates new space in the
memory for value 234 and address or location of value 234 is returned to the variable Y.
• When same variable Y is assigned to variable Z. Here, “=” operator takes the value y(234)
and assigns new space in memory and returns the address back to Z.
• Therefor variable z is not pointing to the location of y. Instead, it is pointing towards new
location in the memory. That’s called Call by value. Changing the variable y will not affect z.
Example:
(function(){
// Do something;
})();
• If you’re inside a specific scope or an object or function, this really means whichever object
you’re in.
• This keyword is an object. At the global level, this keyword points to window object provided
by the JavaScript engine. Window === this.
• In a function/object this keyword points to the owner object of the method/function.
• This keyword can be used in objects(methods), functions too.
Example 1:
let user = {
name: “Avinash”, // property cannot be accessed by any method inside user
LastName: “Nallani”,
getFullName: function() {
console.log(`Full name is ${this.name} ${this.lastName}`) //returns Full na
me is Avinash Nallani
}
}
User.getFullName()
** Here this keyword points to owner object “user”.
Example 2:
let user = {
name: “Avinash”, // property cannot be accessed by any method inside user
LastName: “Nallani”,
age: 25,
getFullName: function() {
console.log(`Full name is ${this.name} ${this.lastName}`) //returns Full na
me is Avinash Nallani
}
}
let user1 = {
name: “Jagadeesh”, // property cannot be accessed by any method inside user1
LastName: “M”,
age: 26,
compare: function(user) {
return this.age>user.age? true: false
}
}
User1.compare(user)
** Here this keyword points to owner object “user1”.
Example 3:
var obj = {
name: "vivek",
getName: function(){
console.log(this.name);
}
Example 4:
var obj1 = {
address : "Mumbai,India",
getAddress: function(){
console.log(this.address);
}
}
What is .call()?
• Using .call predefined method, we can do function/method borrowing from an other object
use that function/method with some other object.
• Call() method allows an object to use method/function of an another object.
Example1:
let user = {
name: “Avinash”, // property cannot be accessed by any method inside user
LastName: “Nallani”,
age: 25,
getFullName: function() {
console.log(`Full name is ${this.name} ${this.lastName}`)
}
}
let user1 = {
name: “Jagadeesh”, // property cannot be accessed by any method inside user1
LastName: “M”,
age: 26
}
Example2:
let user = {
name: “Avinash”, // property cannot be accessed by any method inside user
LastName: “Nallani”,
age: 25,
}
let user1 = {
name: “Jagadeesh”, // property cannot be accessed by any method inside user1
LastName: “M”,
age: 26
}
What is .apply()?
• apply() works as same as .call() method but difference it takes arguments as array.
let user = {
name: “Avinash”, // property cannot be accessed by any method inside user
LastName: “Nallani”,
age: 25,
}
Let getFullName = function(likings) {
console.log(`Full name is ${this.name} ${this.lastName} likes ${likings}`)
}
let user1 = {
name: “Jagadeesh”, // property cannot be accessed by any method inside user1
LastName: “M”,
age: 26
}
What is bind()?
• Bind method returns a new function and later we can invoke that function to get a desired
result.
Example:
let user = {
name: “Avinash”, // property cannot be accessed by any method inside user
LastName: “Nallani”,
age: 25,
}
let user1 = {
name: “Jagadeesh”, // property cannot be accessed by any method inside user1
LastName: “M”,
age: 26
}
Working:
• It will take the copy getFullName function and binds it to user1 object and it will return a
function. And that function can be invoked later.
What is currying?
• Currying is nothing but transforming the function that takes multiple arguments into a
series/sequence of function each taking a single argument of its own.
• If we have a function of f(a,b,c), then currying will transform into f(a)(b)(c).
• Using currying, we are not changing the functionality of the function. We are just changing
the way it is invoked.
function add (a) {
return function(b) {
return a + b;
}
}
add(3)(4)
Working
• Scope represents the accessibility of a particular variables and function in one’s code
• Types Global, local, and block
• Global scope → variable declared in var will have global. It means that variable can accessed
from anywhere inside the code.
• Local/function scope → variable declared in function (let and const) will have local scope.
That can be accessed only in that function. Accessing outside of the function will leads to
reference error
• Block scope → variable that are declared inside {} will have block scope. And can be only
accessed inside the block. Use only let and const. ex: variable i in for loops.
• Scope chain is mechanism in which JavaScript engine uses scope to find the variable. i.e if a
variable is not available in block scope, it checks in the function level scope. If there is no
variable found. It later checks in global scope.
What is closure?
• Closure is technique which is combination of functions that still has access to variable
declared in its outer scope.
Example:
function randomFunc(){
var obj1 = {name:"Vivian", age:45};
return function(){
console.log(obj1.name + " is "+ "awesome"); // Has access to obj1 even when the randomFunc fun
ction is executed
}
}
initialiseClosure();
• We can also say that the ability of a function to store a variable for further reference even
after its is executed, is called closure.
Working.
• In above example, randomFunc() is invoked. It knows it should return a function using obj1
in it.
• So instead of destroying the value of obj1 after execution. It saves the value for later/further
reference.
• This is the reason why the returning function is able to use variable declared in the
outerscope even after the function is already executed.
Example:
Example:
let new Obj = Object.assign(obj1, {lastname: “Nallani”}) // returns { name: “Avinash”, lastname: “Nall
ani”}
Working:
• In above example, we haven’t defined any property called push, delete, and assign. Js is not
throwing error. Because it inherits these properties from its respective prototype.
• In simple words, whenever a property/method doesn’t exists or found in the current array
or current object. It will look for the method/property in the prototype and utilizes them.
Example:
function divideByHalf(sum){
console.log(Math.floor(sum / 2));
}
function multiplyBy2(sum){
console.log(sum * 2);
}
function operationOnSum(num1,num2,operation){
var sum = num1 + num2;
operation(sum);
}
What is memoization?
• Memoization is form of caching where the returned values are stores/cached based on its
parameter in an object.
• Memoization is best suited for compute intense workloads.
Example:
console.log(fib(50))
Working:
• Let’s take an example of getting Fibonacci number for value of 50. If executed normally it
takes more time or even break the server.
• So, in memoization, we are constantly storing every processed data into an object.
• And later we check whether an entry for that is available in memoization. If so then its value
is returned.
• This way we reduce the no of iteration taken by reusing the already computed value.
• Although using memoization saves time. But it leads to large consumption of memory since
we are storing the computed results.
What is recursion?
• Recursion is nothing but ability of a function to call itself repeatedly until it arrives at a
result.
• Important thing to keep in mind while writing recursion is that we should clearly piece out
stopping/end mechanism of iteration.
Example:
function add(number) {
if (number <= 0) {
return 0; // this is the stopping mechanism for the recursive call.
} else {
return number + add (number - 1);
}
}
• Before the introduction of Class in ES6, preferred way was using constructor function.
• Constructor functions are used to create objects in JavaScripts
• When to use constructor function. When we want to create multiple objects having similar
properties but with different values and methods.
• Naming convention of constructor function → Should always written with Pascal
Notation(First Letter capital)
Example:
function Person(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
}
• Introduced in ES6. It provides new and shorted way to write functions/declaring functions.
• Arrow functions can used as a Function expression.
• If your function has only one statement then no need to use the return keyword and {}.
Arrow function will take care of returning the result.
• If your function has more than one statement, you need to include all the statement under
{} and return is must at the end.
• Arrow function are declared without function keyword.
• If arrow function has only one parameter, then no need to include them around parenthesis
().
Example:
• The main difference between function expression and Arrow function are listed below
• Visible syntax differences.
• In Arrow function this keyword always points to the global object i.e., window object.
• Whereas in function expression this keyword points to parent/owner object.
• After ES6, let and const were introduced. Before that we were only using var keyword for
variable declaration.
• Var → global scope, can be re assigned, function scoped, not block scoped
• Let → No global scope, can be re assigned, block scoped.
• Const → no global scope, cannot be re assigned, block scoped.
var c = 15
function test() {
let a = 10;
var b = 11;
const c = 12; // Function scoped so c is 12 even though c is already declared in global scope
console.log(a,b,c) // 10, 11, 12
c = 15 // Cannot assign to 'c' because it is a constant.
{
let x = 9;
console.log(x) // returns 9
var a = 1;
}
console.log(x) // x is not defined.
Console.log(a) // returns 1 bcz var is not block scoped.
}
console.log(b) // b is not defined
console.log(c) // returns 15
test()
What is rest parameter and spread parameter?
Additionally spread operator is used to achieve deep copy for non-primitive data type
Let finalObj = {…obj1, …obj3} // returns { name: “hello”, age: 45, lastname: “hi”, isworking: false }
What is Promise.all()?
Example 1:
var p1 = Promise.resolve(3);
var p2 = 1337;
var p3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(“foo”);
}, 100);
});
• In short, promise.all waits for all promise to get fulfilled. It rejects when it encounters first
reject/error from non-promise and doesn’t care about other promises status.
• If iterables contain non promises inputs, they will be ignored but still counted in returned
promise array value.
Promise.all([
p1.catch(error => { return error }),
p2.catch(error => { return error }),
]).then(values => {
console.log(values[0]) // "p1_delayed_resolution"
console.error(values[1]) // "Error: p2_immediate_rejection"
})
What is promise.any()?
• Just as its name says “any”, which means it returns as soon as any one of the iterables gets
fulfilled.
• Accepts iterables of non-promises too
• It rejects with Aggregate Error when none of the iterables was fulfilled.
• It rejects upon receiving empty iterables whereas promise.all won’t reject if passed with
empty iterables.
• It should be used only if the tasks are dependent on each other.
• Just like promise.any, it resolves as soon as one of its promises fulfils. But in promise.race()
reject is also considered.
• Empty iterable to race returns “promise to be forever pending”.
• Accepts iterables of non-promises too.
What is Promise.allsettled()?
• Waits until all the promises have been settled (each promise might have resolved or
rejected)
• Takes the input as iterables of promises. Then returns the array of response which describes
the outcomes of each promise. It also takes non promise as iterables too.
• Used only if you have non synchronous tasks that are not dependent on one another to
complete successful.
Example: