InterviewSolution
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. 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. Now the add(2) will be called and will be expended into “2 + add(1)”. Finally the add(0) will trigger the termination condition If(n≤0) and produce 0. |
|
| 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. 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. 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 NaNEverything 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 1Now, 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-324Now, 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). |
|
| 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. |
|
| 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. |
|
| 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. //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 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 this is Object itself “this” with constructor function 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. 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. 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”. 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. |
|
| 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 So, every language have a way of handling the value of a variable between function declaration and definition. 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(===)
Type-converting comparison 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. |
|
| 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. 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.
If no ERROR it will generate an executable “hello” and we will run it by: ./hello
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.
However there is a compilation step just before the interpretation step in JavaScript. So, JS is both compiled and interpreted language.
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.
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. |
|