Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

151.

Explain callback functions in JavaScript?

Answer»

 A Higher Order Function is a function that TAKES one or more function as argument. We use them at many places in JavaScript, and are also called callback functions.

Consider, the below JS code which uses filter to filter-out Adult people. Here, we have a callback function isAdult  which is called on every item.

These callbacks are USUALLY DEFINED inline as anonymous function. So, the REFACTORED code is below.

 We can further refactor it using arrow functions as below.

So, the array METHODS of map(), filter(), reduce(), forEach() are all Higher Order Functions.

Beside this eventListener like below are also Higher Order Function, as they use a callback function.

152.

What are promises JavaScript?

Answer»

Recursion is a technique for iterating over an operation by having a function call itself repeatedly until it arrives at a result.
Now, in recursive function there are two parts. One is termination condition and other is the recursion itself.  The termination condition is very important or else the recursion never stops and goes into infinite loop. 

Let consider the below simple example to add numbers from the CURRENT passed number BACKWARDS till 1. Say we pass 3, then 3+2+1 = 6. In the below example If(n≤0) is the termination condition and return n + add(n-1); is the recursion. 

The recursion works as shown in the diagram below.
It works like loop, so the first call will go to recursion part and GIVE “3 + add(2)”. 

Now the add(2) will be called and will be expended into “2 + add(1)”.
After that add(1) will be called and expanded into “1 + add(0)”. 

Finally the add(0) will trigger the termination condition If(n≤0) and produce 0.
After this everything will be added 3 + 2 + 1 + 0 to give 6.

153.

What is IIFE in JavaScript?

Answer»

 A callback function, also known as a higher-order function, is a function that is passed to another function as a parameter, and the callback function is executed inside the that Function.

Callback function are USED everywhere in JavaScript. In JavaScript, functions are first-class citizens. They can be “stored in variables, passed as arguments to functions, created WITHIN functions, and returned from functions”.

Let’s look at the example below. Here we call function mainFunc with function “x” as argument and then from inside mainFunc, calling it after some CONSOLE log.

When we use anonymous function inside our function call for callback LIKE in the below code.

The in-built for Each, map, reduce, filter uses callback functions internally. CHECK the below example and here we are passing a function, just like above calc code.

154.

What is event bubbling and capturing in JavaScript?

Answer»

Promises in JavaScript are like promises in real life. You promise to do SOMETHING, and then it is done or not done. A promise may be in one of 3 possible states: resolve, rejected, or pending.

They are mainly used to do asynchronous task like calling a REST api and GETTING the result back. So, these network CALLS takes TIME. When the network call is been made, the promise is in Pending state. Once the network call is successful the promise returns a resolve and if it fails it returns resolve.The resolve is CAPTURED by the then() callback function and reject captured by catch() callback function.

Consider the below example. Here inside promiseCleanRoom we generate a random number between 0 and 1. If the number is greater the 0.5, we send a resolve or else we send a reject.
Depending on the case either .then is executed or .catch is executed.

Below is the resolve case

155.

b let i = ? console.log(i * i); //Gives 0 console.log(i + 1); //Gives 1 console.log(i - 1); //Gives -1 console.log(i / i); //Gives 1

Answer»

 IIFE MEANS Immediately Invoked Function Expression. Let’s first see a normal way to create function in JavaScript, also known as function as “Function DECLARATION”. This is most SIMILAR, to the syntax of declaring functions in most other traditional languages like C++ and Java.

Consider the below example which have a simple function to add two numbers. Notice that these function definitions always start with the function keyword. You can’t omit it as it’s invalid syntax.

In JavaScript functions are first CLASS citizens. So, there is another way to DECLARE them. It is known as “Function Expression”.  We will refactor the above addNumbers() code. Here we are treating as if addNumbers is a variable declaration. But then assigning an anonymous function to it.

IIFE(Immediately Invoked Function Expression) is nothing but a function expression, but it is defined and invoked at the same time. Here we had got rid of the addNumbers name itself and calling it also at the same time. Notice, that we are passing 2,3 immediately after the anonymous function is declared.

As JavaScript for most part is function scoped, so IIFEs are great way to create private variables.

156.

What should be the value of “i” so that we get the mentioned result?

Answer»

When an event happens on an element, it first runs on which it was clicked, then on its PARENT, then all the way up on other ancestors. It is the default behaviour of the browser.

Event CAPTURING is the opposite of bubbling and it means when you CLICK on parent element, it GOES till the child.

We will first see Event Bubbling. The HTML contains an parent element containing a child element called Child1. When we click on the “Child1” button, first the console log of child is displayed and then the parent is displayed.

We will now see Event Capturing. The HTML contains an parent element containing a child element called Child1. When we click on the button, first the console log of parent is displayed and then the child is displayed. Notice that in addEventListener we have to pass a value of true.

157.

What is the issue with the below code and how it can be fixed? const array = [1, 2, 15, 4, 30, 7, 45]; console.log(array.sort());

Answer»

The most obvious answer to think is the value of “i” will be 0. So, LET’s put i = 0 and see what happens.

let i = 0; console.log(i * i); //Gives 0 console.log(i + 1); //Gives 1 console.log(i - 1); //Gives -1 console.log(i / i); //Gives NaN

Everything is ok, but the LAST one produce NaN(Not a Number) because “0 divide by 0 will produce infinity”

So, we need a number which is like zero but gives 1 if we divide it by itself. Fortunately there is such a number in JAVASCRIPT. The number is the minimum value that is allowed in JavaScript and is represented by Number.MIN_VALUE

let i = Number.MIN_VALUE; console.log(i * i); //Gives 0 console.log(i + 1); //Gives 1 console.log(i - 1); //Gives -1 console.log(i / i); //Gives 1

Now, what is this MIN_VALUE and why it produces the above correct DESIRED result. If we console log it we can see it’s a very small number 5e-324.

console.log(Number.MIN_VALUE); //5e-324

Now, this number in most cases behaves like a zero(0). Like when we multiply it by itself(i * i), add it to 1(i + 1) or SUBSTRACT it from 1(i -1).
But when we divide this small number by itself it produces 1.

158.

var A = {    x: function() {        console.log('x');    },    y: function() {        console.log('y');    },    z: function() {        console.log('z');    }     } A.x().y().z();

Answer»

The sort() method is used to sort the elements of an array. But the output of the above is not what expected out of sort() function. The output will be [ 1, 15, 2, 30, 4, 45, 7 ] and it is far from desired.

This is because the default sort is ACCORDING to TRING Unicode points. The fix to it is by ADDING an anonymous function and tell to sort according to ascending or descending order. 

Ascending order is as below:

CONST array = [1, 2, 15, 4, 30, 7, 45]; console.log(array.sort((a, b)=> a-b)); //[ 1, 2, 4, 7, 15, 30, 45 ]

Descending order is as below:

const array = [1, 2, 15, 4, 30, 7, 45]; console.log(array.sort((a, b)=> b-a)); //[ 45, 30, 15, 7, 4, 2, 1 ]
159.

What should be changed in the below code that it prints x, y and z?

Answer»

The output right now will be as below, as the method CHAINING is not understood by the compiler.

/* Exception: TYPEERROR: A.X(...) is undefined @Scratchpad/1:14:1 */

We can GET the desired output by “return this” in each function.
Now “this” is the object “A”. So, A.x() will result in CONSOLE logging ‘x’ followed by returning the object “A” to y().
After that the function A.y() will print ‘y’ followed by returning the object “A” to z().
Finally, ‘z’ is printed on console.

var A = {     x: function() {         console.log('x');         return this;     },     y: function() {         console.log('y');         return this;     },     z: function() {         console.log('z');         return this;     }  } A.x().y().z();  //Output x y z
160.

Explain the concept of hoisting in JavaScript?

Answer»

Hosting means we can use a variable even before declaring it. When the compiler RUNS(details in Question 1) and finds all the var declaration, it MOVE them to the top of the file.

Let’s consider this below example. Here we are assigning values to  on name , age and profession without declaring them first. They are declared on line 8, 9, 10 and yet the interpreter doesn’t throws a runtime error. It is because it doesn’t matter where the VARIABLES are declared. They are always hoisted to the top by when the compiler makes the first pass.

name = "Thomas"; age = 45; profession = "Engineering Manager";   console.log(`${name} aged ${age} is ${profession}`); //Thomas aged 45 is Engineering Manager   var name; var age; var profession;

This is also true for function declaration, as the compiler also treats function declaration as variable declaration as in JS all function declaration are object declaration. But same is not true for function expression and it will give reference error. 

console.log(funcDeclaration()); //Function declaration console.log(funcExpression());  //ReferenceError   function funcDeclaration() {   console.log('Function declaration'); }   let funcExpression = function() {   console.log('Function expression'); } /*

Exception: ReferenceError: can't access lexical declaration `funcExpression' before initialization

@Scratchpad/7:2:1

*/

But why did we got this Reference error in function expression call. This is to do with the compiler and interpreter step in JavaScript, which we UNDERSTOOD in Question 1.
The compiler runs first and finds all the “var” , and the function declaration are also treated as variable declaration because in JS all function declaration are object declaration.
So, the function declaration call doesn’t give as any error.

But the same is not true about function expressions. Here when the compiler runs it registers a variable functionExpression at line 8, but it doesn’t knows what it is. So, when the interpreter runs at line 2, it throws a runtime error, because it doesn’t know what is functionExpression.

161.

What is the difference between for..in and for..of loops?

Answer»

ONE The for..in LOOP is mainly used to iterate over properties of an Objects.
In JAVASCRIPT Arrays are also Objects and each characters in an string have an index. So, we can use them also to iterate over Arrays and Strings also.

//Object example

const OBJ = {   'frontend developer': 'Thomas',   'designer': 'Mary',   'backend developer': 'Harry',   'engineering manager': 'Vikas' }   for(const key in obj) {   console.log(`${key}: ${obj[key]}`) } 

//Array example

const array = ['frontend developer', 'designer', 'backend developer', 'engineering manager']; for(const index in array){   console.log(array[index]); }

//String example

const string = 'frontend developer'; for(const index in string){   console.log(string[index]); }

The for..of loop was introduced in ES6 and is used to iterate over Objects that have [Symbol.iterator] property. This includes array, strings, Map, Set and NodeList. They cannot be used to iterate over Objects are not iterable.

If we check the __proto__ of an array, we can find the [Symbol.iterator] property.

But it is not the case with Objects as it is not iterable.

Some use of for..of loop are below:

//Array example

const array = ['frontend developer', 'designer', 'backend developer', 'engineering manager'];

for(const item of array){   console.log(item); }

//String example

const string = 'developer'; for(const char of string){   console.log(char); }

//Map example

const map = new Map();   const emp1 = {name: 'Vikas', Degree: 'MS'}; const emp2 = {name: 'Thomas', Degree: 'MBA'};   map.set(emp1, 'frontend developer'); map.set(emp2, 'engineering manager');   for(const [key, item] of map) {   console.log(key, '-', item); }

162.

Explain ”this” in JavaScript?

Answer»

JavaScript “this” keyword simply means that WHATEVER scope you are inside, it belongs to that. Now the scope can be a function or and Object. Although, there are some exception to this rule. We can have “this” in various context. Let’s go through them.

“this” in simple function
In a NORMAL JS function like below, the “this” refers to global window object.

function foo() {   console.log(this);   console.log(this === window);   } foo();

Running the above code will give.

There is a special case with strict MODE.

In strict mode “this” to be UNDEFINED , as global object refers to undefined instead of window object. 

function foo() {   'use strict';   console.log(this);   console.log(this === window);   } foo();

“this” in an object property
In an object which have a property as a function, the value of “this” is the Object itself.

var obj = {}; obj.foo = function() {   console.log("Inside obj foo");   console.log(this); } obj.foo();

this is Object itself

“this” with constructor function
When a function is called with “new” keyword, it is known as constructor function. And the value of “this” refers to the newly created instance.

function Person(FN, ln) {  this.first_name = fn;  this.last_name = ln; this.displayName = function() {     console.log(`Name: ${this.first_name} ${this.last_name}`);     console.log(this);  } } let person = new Person("Tim", "Horton"); person.displayName();   let person2 = new Person("Mary", " Poppins"); person2.displayName();

The newly created instance is nothing but an object, because everything in JS is an object.

163.

What is a closure and how do we use it?

Answer»

Closures are one of the most complex topic in JavaScript, but they are everywhere in JavaScript.

Closures are basically, the inner function having access to the variables in the outer function scope, even after the outer function has returned. To use a closure, SIMPLY define a function inside another function and expose it. To expose a function, return it.

Consider the below code. The variable b have an scope in outer function i.e. from LINE 4 to line 10. So, at line 13 when we call the outer function, it can access the value of b, but at line 14 there is no outer function.

So, how does the innerFn() access the value of b. This is where the JS feature of Closures comes into play.

When the “VAR inner” is created at line 6, the JS engine not only stores the function object information but also its scope information. So, it stores a scope of variable b inside the inner function object.

Now it doesn’t matter where you call inner, whether in this file or some third party file. It will ALWAYS remember the value of a and b, as if a snapshot is been taken.

var a = 10;   function outer() {   var b = 20;      var inner = function() {     console.log(a);     console.log(b);   };   return inner; }   var innerFn = outer(); innerFn();  

Output

//10 //20
164.

What is difference between function declaration and function expression ?

Answer»

Function declaration is like most other TRADITIONAL languages, but in JavaScript we use the keyword “function”.
In function expression we assign an anonymous function to an variable. They are very useful when we pass function as arguments to other function or return an function.

function funcDeclaration() {   console.log('Function declaration'); }   let funcExpression = function() {   console.log('Function expression'); }   console.log(funcDeclaration()); //Function declaration console.log(funcExpression());  //Function expression 

One of the key difference is that, we can CALL a function declaration even before defining it but same is not true for function expression and it will give reference error. Let’s move both the function call to the top. 

console.log(funcDeclaration()); //Function declaration console.log(funcExpression());  //ReferenceError   function funcDeclaration() {   console.log('Function declaration'); }   let funcExpression = function() {   console.log('Function expression'); }

/*

Exception: ReferenceError: can't access lexical declaration `funcExpression' before initialization

@Scratchpad/7:2:1

*/

But why did we got this Reference error in function expression call. This is to do with the compiler and interpreter step in JavaScript, which we understood in Question 1. 
The compiler runs first and finds all the “var” , and the function declaration are also treated as variable declaration because in JS all function declaration are object declaration. 
So, the function declaration call doesn’t give as any error.
But the same is not true about function expressions. Here when the compiler runs it registers a variable functionExpression at line 8, but it doesn’t KNOWS what it is. So, when the interpreter runs at line 2, it throws a runtime error, because it doesn’t know what is functionExpression.

165.

What is the difference between null and undefined ?

Answer»

Both null and undefined  represents empty VALUES. Let’s understand them first and then we will see what is the difference.

undefined
To understand “undefined” we have to understand what is declaration and definition of variables. When we declare a variable as in below diagram by “var VALUE, the compiler MAKES space for a variable “value”. The definition means that we assign a value to the variable and it’s allocated in that space. You can also do these two together by
var value = 42;

So, every language have a way of handling the value of a variable between function declaration and definition.
In JavaScript that is handled by TYPE “undefined”. The type undefined is a primitive type which have only one value possible i.e. undefined. 

null
It is also similar to “undefined” and is a primitive type. It also have only one possible value i.e. null. It is also used to represent empty values, but is generally ASSIGNED by the users.

var a; console.log(a); //undefined  a = null; console.log(a); //null
166.

What is the difference between == and === ?

Answer»

 JavaScript has both strict and type-converting equality comparison. For strict comparison we use === and for type-converting comparison we use == . LET’s look at each of it in details :

Strict Comparison(===)
For strict comparison the items been compared must be the same type.

  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in CORRESPONDING positions. 
console.log("Coder" === "Coder"); //true console.log("Coder" === "coder"); //false
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
console.log(23 === 23); //true console.log(NaN === NaN); //false console.log(0 === -0); //true 
  • Two Boolean operands are strictly equal if both are true or both are false.
console.log(true === true); //true console.log(false === false); //true
  • Two objects are strictly equal if they refer to the same Object.
VAR obj = {}; var newObj = obj; console.log(newObj === obj); //true
  • Null and Undefined TYPES are not equal
console.log(null === undefined); //false console.log(null == undefined); //true

Type-converting comparison
The == does a type conversion before comparing, if both items are of different types. 

As you can see in the below example. String 1 is equal to NUMERIC 1, when using ==. It is because the type of String 1 is converted to Number before comparison. 
It is the similar case with “1 == true”. The 1 is converted into Boolean, which is true before comparison.
Same expressions are not true while using ===, as we know it doesn’t do any type conversion.

console.log('1' == 1); //true console.log(1 == true); //true console.log(1 === true); //false console.log('1' === 1); //false
167.

What is the difference between keyword let, const and var ?

Answer»

The variable “var” was since the beginning of JavaScript i.e. since 1997. So, if someone didn’t updated there browser since the beginning(or past 10 years) the keyword “var” will only work on there browser. 

The variables "let” and “const” were introduced recently in ES6(In 2015).  There were some design mistakes made with “var” and these were rectified with “let” and “const”. 

The problem is that “var” is FUNCTION scoped and it causes a lot of problems.
Consider the below example where we are USING “var” inside a traditional “for” loop. But we are also able to access and update “i” outside of the “for” loop.

for(var i=0; i<5; i++) {   console.log(i); //Output- 0 1 2 3 4 }   i = i + 2; console.log(i); //Output- 7

Since, “var” is function scope so we can put our “for” loop inside a function and then “i”  won’t be accessible outside.

function incrementI() {     for(var i=0; i<5; i++) {     console.log(i);    } }   incrementI(); //Output- 0 1 2 3 4i = i + 2; console.log(i);

//Output- 

/* Exception: ReferenceError: i is not defined @Scratchpad/6:9:1 */

 Traditional languages like C, C++ and Java as they are blocked scope and it is what was desired from JavaScript. So, the variable “let” and “const” introduced in 2015 were made block scoped.

 The “for” loop declared with “let” will also throw an error, when we try to access “i” outside of it. It is because the scope of “i” ends with the “for” loop.

for(let i=0; i<5; i++) {     console.log(i);  //Output- 0 1 2 3 4 } i = i + 2; console.log(i);

//Output-  

/* Exception: ReferenceError: i is not defined @Scratchpad/6:6:1 */

We will understand “const” now. It is similar to “let” and have block scope. But it was created to declare constant variables in JavaScript. We cannot assign a new value to a variable after the initial declaration for primitive types like INTEGERS and strings.

const c = 12; c = 14; console.log('c is ', c);

/*

Exception: TYPEERROR: invalid assignment to const `c'

@Scratchpad/6:2:1

*/

But can add or update values for non-primitive like arrays and objects. 

const arr = [1, 2, 3]; arr.push(4); console.log('arr is ', arr); // [ 1, 2, 3, 4 ]   const obj = { name: 'Robin', skill: 'JS' }; obj.skill = 'React'; obj.profession = 'Developer'; console.log('obj is ', obj);  // { name: "Robin", skill: "React", profession: "Developer" }
168.

Is JavaScript an interpreted language or compiled language?

Answer»

Let’s first understand what is an compiled language and interpreted language.

  • Compiled LANGUAGES are languages in which we turn a program first from human-readable format to machine format, generally through a compiler. After that we execute that code. So, it is generally a two-step process. Languages like C, C++ and Java are example of Compiled languages. For example if we have a “C” program(hello.c), we will first convert it into machine code by using a gcc(gnu C compiler) like below:
gcc hello.c -o hello

If no ERROR it will generate an executable “hello” and we will run it by:

./hello
  • Interpreted Languages are languages in which code doesn’t needs to be compiled first. Language like Perl, Python are interpreted languages. To run a python code we just need to run it directly by command like below:
python hello.py

The above code does not need to be compiled first but it does require that python is installed on any machine that needs to run the script.

  • JavaScript is a special case where you directly execute your source code. A webpage will directly execute your JavaScript. So, for that reason many people think JavaScript as a interpreted language.

However there is a compilation step just before the interpretation step in JavaScript. So, JS is both compiled and interpreted language.

  • Compilation Step – During this step the compiler MAINLY registers the variable declarations.

Let consider the below example. The compilation steps mainly looks at the var keyword. It is not BOTHERED with what is assigned in these variables.

var a = 10; var b = 20; console.log(a+b)

When the compiler goes to line 1, it encounters var a and registers it in the global scope and then goes to line 3 and registers the var b. Line 5 is only a console and it doesn’t finds any var, so don’t do anything.

  • Interpretation Step – During this the actual execution takes place. 

For the above example, the interpreter starts at line 1 and see a variable a and ask the compiler, if it have a variable “a” in Global scope and the compiler have it. So, it assigns the value 10 to it. Next the same step is repeated for line 3 and interpreter assigns 20 to variable “b”. 

Now once the interpreter goes to line 5, it finds console. It first looks for console at global scope from the compiler but don’t find it. So, it checks in the JavaScript global and finds it. Inside the console there are variable a and b, which it finds at global scope. It then adds them using addition operator and display the result.