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.

1.

Which event occurs when a value is added in an input box 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.

2.

What is the usage of onpagehide event in JavaScript?

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
3.

When an onfocus event is triggered in JavaScript?

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.

4.

Which event triggers in JavaScript when an object loses focus?

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
5.

What are logical errors in JavaScript?

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
6.

Join the elements of an array into string with a separator in JavaScript

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" }
7.

How to fill static values in an array in JavaScript?

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.

8.

Why do we use onabort event in JavaScript?

Answer»

The oninput event occurs when a value is included in the input box. This is how we can set the oninput event: 

<input TYPE="text" id="display" oninput="display()">Above, the function display() is called when a user BEGINS adding value in the textbox: function display() {     VAR a = document.getElementById("display").value;     document.write("Typed: " + a); }
9.

When the onresize event executed in JavaScript?

Answer»

<P>When a visitor leaves the web page, then the onpagehide event TRIGGERS. The visitor can move to another page or click a link after leaving the current web page. An example here displays an ALERT box when the user tries to leave the page. This happens since onpagehide event fires when the page is left: 

<!DOCTYPE html> <html> <body onpagehide="display()"> <p>Close the page</p> <script> FUNCTION display() {     alert("It was NICE having you here!"); } </script> </body> </html>
10.

Why do we use of every() method in JavaScript?

Answer»

In JavaScript, an onfocus event is TRIGGERED when ELEMENT gets focus. An example here displays that a USER TYPES in the TEXTBOX and the onfocus event is triggered, allowing the color of the text to change to yellow: 

<!DOCTYPE html> <html> <body> <h2>Type your name</h2> <input type="text" onfocus="display(this)"> <script> function display(z) {     z.style.color = "yellow"; } </script> </body> </html
11.

Why do we use some() method in JavaScript?

Answer»

The blur event triggers when object loses focus. An EXAMPLE here displays that we write a name in the textbox and then when the object loses focus, the text COLOR is changed. This happens SINCE the blur event triggers when the focus ends: 

<!DOCTYPE HTML> <html> <body> <h2>Type your name</h2> <input type="text" onblur="display(this)"> <script> FUNCTION display(z) {     z.style.color = "green"; } </script> </body> </html>
12.

How to set the page-break behavior after an element with JavaScript?

Answer»

LOGIC ERRORS occur when there is a MISTAKE in the logic. This can lead your SCRIPT to work INAPPROPRIATELY to give unexpected results.

13.

How to detect a mobile device with JavaScript?

Answer»

Use the JOIN() method to join the elements of an ARRAY into string with a separator. An example here: 

<!DOCTYPE html> <html> <body> <SCRIPT> var ARR = ["abc", "def", "ghi", "jkl"]; document.write("INITIAL array = "+arr); document.write("<br>Updated array = "+arr.join(" demo ")); </script> </body> </html>

Above, we have joined the elements into a string with a separator. 

The output is: 

Initial array = abc,def,ghi,jkl Updated array = abc demo def demo ghi demo jkl
14.

Why do we fill columns with JavaScript?

Answer»

You can fill static VALUES in an array using the fill() method in JavaScript. An example is here:

<!DOCTYPE html> <html> <body> <script> var ARR = ["ABC", "def", "ghi", "jkl"]; document.write("INITIAL array = "+arr); document.write("<br>UPDATED array = "+arr.fill("pqr",1,2)); </script> </body> </html>

The output displays that the array is set with static value: 

Initial array = abc,def,ghi,jkl Updated array = abc,pqr,ghi,jkl
15.

How to find the coordinates of the cursor relative to the screen with JavaScript?

Answer»

The onabort EVENT is executed when the loading of an image is aborted. Use it in an image TAG like this:

<img src="demo_image.jpg" onabort="display()"&GT;

Here, you can display an alert when the loading of image ABORTS

function abortFunc() {   alert('Image isn’t loading!'); }
16.

Why Browser Object Model (BOM) introduced in JavaScript?

Answer»

The onresize event is executed a JavaScript when the browser window is resized. An example here displays the same:

&LT;!DOCTYPE html&GT; <html> <head> <script> function display() {    var a = "Window Width=" + window.outerWidth + ", Window Height=" + window.outerHeight;    document.getElementById("myid").innerHTML = a; } </script> </head> <body onresize="display()"> <p>Resize browser window!</p> <p id="myid"> </p> </body> </html>

The above displays the FOLLOWING OUTPUT when the window is resized: 

Resize browser window! Window Width=1366, Window Height=728
17.

How to get the count of forms in a document with JavaScript?

Answer»

JavaScript array every METHOD checks whether the array elements (all) passes the test. A condition is checked for the test. An EXAMPLE here checks for every elements in the array for a condition passed in the function:

<!DOCTYPE html&GT; <html> <body> <script> var val = [128, 29, 28, 45]; function DISPLAY(a) {     return a > 21; } document.write("Are all the values greater than 21 in the array = "+val.every(display)); </script> </body> </html>

The output displays true since the condition is satisfied for all the elements of the array.

18.

Can we preserve the readability of text when font fallback occurs with JavaScript??

Answer»

The some() method checks if an array element satisfies a TEST. An example:

&LT;!DOCTYPE html> <html> <body> <script> var val = [20, 28, 45]; function display(a) {     return a > 21; } document.write("Are their VALUES greater than 21 in the array = "+val.some(display)); </script> </body> </html>

The OUTPUT is true i.e. we have tested the array element and checked a condition: ELEMENTS greater than 21.

19.

Why AES was introduced in JavaScript?

Answer»

The pageBreakAfter property in JavaScript is USED set the page-break behavior after an element. LET’s say you NEED to set if got footer: 

FUNCTION MYFUNC() {    document.getElementById("idFooter").style.pageBreakAfter = "always"; }
20.

How to check whether entered value is NaN in JavaScript?

Answer»

To detect a mobile device, LET’s say Android device, USE the navigator.userAgent.match. Here, we have set it in a function: 

Android: function() {             RETURN navigator.userAgent.match(/Android/i);         },

For IOS

   iOS: function() {             return navigator.userAgent.match(/iPhone|iPad/i);         },
21.

How to add 15 minutes to a JavaScript Date

Answer»

The columnFill property is used in JavaScript to fill columns. It means you can divide your content in columns LIKE 2 3, 4, columns on a web page. An EXAMPLE is shown below: 

<!DOCTYPE html> <html> <body> <p>Create columns...</p> <BUTTON onclick="display()">Columns</button> <div id="demo"> Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! Example Paragraph! </div> <SCRIPT> function display() {     document.getElementById("demo").style.columnCount = "2";     document.getElementById("demo").style.columnFill = "balance"; } </script> </body> </html>

The above text is divided into two columns since we have SET columnCount as 2:

22.

Difference between parseInt(string) and Number(string) in JavaScript?

Answer»

To interact with the BROWSER, the Browser Object MODEL has some properties and methods. Some examples include, the height and width of the WINDOW/ screen.

Some of its methods include:

  • window.open() – To open a new window
  • window.close() – To close the CURRENT window
  • window.moveTo() – To move the current window
  • window.resizeTo() – To RESIZE the current window
23.

Round a number to specified decimal place in JavaScript

Answer»

Use the document.forms length property of forms to count the number of forms in a document. Here’s an example for the same: 

<!DOCTYPE HTML&GT; <html> <body> <form> NAME: <input type="text" name="my_name" value="DEMO"> Password: <input type="password" name="pwd" value=""> <input type="submit" value="Submit"> </form> <script>   var res = document.forms.length;   document.write("<br>Count of forms = "+res); </script> </body> </html>

The output displays the count: 

24.

Convert the arguments object to an array in JavaScript

Answer»

Yes, we can PRESERVE the readability of text USING the FONTSIZEADJUST PROPERTY. This sets the difference between lowercase and uppercase LETTERS size.

25.

How to create a custom object in JavaScript?

Answer»

Advanced ENCRYPTION Standard (AES) encrypts the data in the application. To perform AES, the JavaScript library FORGE is used.

 An example for encryption can be string encrypted to store in the DATABASE.

26.

How to delay a JavaScript function call using JavaScript?

Answer»

To check whether a value entered is a NaN or not, use the Number.isNaN() method. This method returns true if the value is not a number, else false is RETURNED.

Let’s say the following is our value:

VAR a = 'z';

To check whether it is a number or not, use isNaN() method: 

isNaN(a);

The following is an example that returns true i.e. not a number: 

&LT;!DOCTYPE html&GT; <html> <body> <SCRIPT>     var a = 'z';     document.write(isNaN(a)); </script> </body> </html>

The output: 

true

Let us see another example: 

<!DOCTYPE html> <html> <body> <script>     var a = 0/0;     document.write(isNaN(a)); </script> </body> </html>

The output generates True since 0/0 is not a legal number:

True

Let us see another example that is a number. Therefore, false is returned: 

<!DOCTYPE html> <html> <body> <script>     var a = 50;     document.write(isNaN(a)); </script> </body> </html>

The output:

false
27.

Is it possible to create a custom alert box in JavaScript?

Answer»

The getMinutes() method is provided by JavaScript to get the current minutes in  JavaScript. The minutes are according to LOCAL time. We will add minutes to it using the setMinutes() method.

Create a DATE object:

VAR date = new Date();

Now get the current date and time: 

// current date and time document.write("Current Date and Time = "+date);

Now, under setMinutes(), get the current minutes using getMinutes() and add the minutes as shown below. We added 10 minutes here: 

date.setMinutes(date.getMinutes() + 10 );

The following is an example to add 15 minutes to a date in JavaScript: 

<html>    <head>       <TITLE>JavaScript setMinutes() Method</title>    </head>    <body>       <script>          var date = new Date();          // current date and time          document.write("Current Date and Time = "+date);          date.setMinutes(date.getMinutes() + 15 );          document.write("<br>New Date = "+date);       </script>    </body> </html>

The output: 

Current Date and Time = Sat Dec 15 2018 20:11:14 GMT+0530 (India Standard Time) New Date = Sat Dec 15 2018 20:26:14 GMT+0530 (India Standard Time)
28.

How and why to use leading bang! in JavaScript function?

Answer»

Let’s say the following are our arrays:

[20, 40, 60] [80, 100, 120]

To merge them, JavaScript provides the Array.concat() method. The return value of this method is a new array with the result of concatenated arrays: 

var res = arr1.concat(ARR2);

Let us now merge the above two arrays: 

&LT;html>    <head>       <title>Merge JavaScript Arrays</title>    </head>    <BODY>       <script>          var arr1 = [20, 40, 60];          var arr2 = [80, 100, 120];          document.write("Array 1 = " + arr1);          document.write("<br>Array 2 = " + arr2 );          var res = arr1.concat(arr2);          document.write("<br>Merged Arrays = " + res );       </script>    </body> </html>

The OUTPUT displays the merged arrays:

Array 1 = 20,40,60 Array 2 = 80,100,120 Merged Arrays = 20,40,60,80,100,120
29.

Format numbers as currency string in JavaScript

Answer»

The parseInt() method parses up to the FIRST non-digit and returns the parsed value, whereas Number() converts the string into a number, which can also be a float.

To learn about the difference between parseInt(string) and Number(string) in JAVASCRIPT, let us see an example:

Let’s SAY we have the following value:

20demo

Using parseInt(string), 20 is returned:

<!DOCTYPE html> <html> <body> <script>   document.write(parseInt("20demo")); </script> </body> </html>

The output: 

20 

Using the Number(string), the same value returns NaN:

<!DOCTYPE html> <html> <body> <script>   document.write(Number("20demo")); </script> </body> </html>

 The output:

NaN  

Let us now WORKAROUND for a float value with both Number(string) and parseInt(string): 

<!DOCTYPE html> <html> <body> <script>   document.write(Number("12.99demo"));   document.write("<BR>"+parseInt("12.99demo")); </script> </body> </html>

The output: 

NaN 12
30.

Why do we use a plus sign in front of function name in JavaScript?

Answer»

To round a number to specified decimal place in JavaScript, the toFixed() method is to be used.

Let us first SEE the syntax;

number.toFixed( [digits])

Here, digits is the decimal places to be set. For example, for 1 decimal place:

variable.toFixed(1))

The following is an example to round a number to 2 decimal places in JavaScript:

&LT;html&GT;    <head>       <title>JavaScript toFixed()</title>    </head>    <BODY>       <script>          VAR a = 291.78687;          document.write("Number = " + a);          document.write("<br>Result (2 decimal places) = " + a.toFixed(2));       </script>    </body> </html>

The output: 

Number = 291.78687 Result (2 decimal places) = 291.79

Let us see another example wherein we will round a number to 3 decimal places in JavaScript: 

<html>    <head>       <title>JavaScript toFixed()</title>    </head>    <body>       <script>          var a = 291.78687;          document.write("Number = " + a);          document.write("<br>Result (3 decimal places) = " + a.toFixed(3));       </script>    </body> </html>

The output: 

Number = 291.78687 Result (3 decimal places) = 291.787
31.

Why JavaScript 'var null' throw error but 'var undefined' doesn't?

Answer»

The Array.from() method is used in JavaScript to convert the arguments object to an array.

Let us FIRST see what Array.from() method PROVIDES us:

Array.from(obj, mapFunction, thisValue)

Here,

  • obj: The object which is converted to array
  • mapFunction: Map Function to be called
  • val: Value to be used as this while executing the map function.

Here, we have a function, which we are calling with some values:

display('q', 'w', 'h', 'm', '20', '66', '35')

The display() function CONSIDER arguments and sets using the Array.from() method. With that the sort() method is used to sort the array for our example: 

function display(){    var myArgs = Array.from(arguments);    return myArgs.sort(); }

The following is an example to convert the arguments object to an array: 

<!DOCTYPE html> <html> <BODY> <script>   function display(){     var myArgs = Array.from(arguments);     return myArgs.sort();   }  document.write(display('q', 'w', 'h', 'm', '20', '66', '35')); </script> </body> </html>

The output:

20,35,66,h,m,q,w
32.

Explain how Inheritance works in constructor Functions?

Answer»

Create a custom object in JavaScript, using the “new”. It is followed by the constructor method Object():

var department = new Object();

Let us see an example to create a custom object in JavaScript: 

<html>    <head>       <TITLE>Custom objects</title>       <script>          var department = new Object();          department.name = "Finance";          department.ID  = 005;          department.location = "North";       </script>    </head>    <body>       <H2>Department Details</h2>       <script>          document.write("Department Name = " +  department.name + "<br>");          document.write("Department Id = " + department.id + "<br>");           document.write("Department Location = " + department.location);       </script>    </body> </html>

The output: 

Above, firstly we have created an object:

var department = new Object();

After that properties are ASSIGNED

department.name = "Finance"; department.id  = 005; department.location = "North";
33.

Explain Prototype chain in JavaScript using Object.create()?

Answer»

The setTimeout() function is used in JavaScript to delay a function call.

For example, if you want to delay the function call by 5 seconds, then you can easily achieve this using the setTimeout() function.

The following is the syntax:

setTimeout(func_name, milliseconds, arg1, ARG2, ...)

Here,

  • func_name: Name of the function to be executed.
  • milliseconds: Number of milliseconds.
  • arg1, arg2 Arguments PASSED to the function.

The following is an example:

Let’s say we want the function cal to delay by 3 seconds, therefore we will implement the setTimeout( with a parameter as 3000 milliseconds (i.e. 3 seconds):

function display() {     setTimeout(function(){ document.write("Displaying after 3 seconds..."); }, 3000); }

The example: 

<!DOCTYPE html> <html> <BODY> <button onclick="display()">Click</button> <SCRIPT> function display() {     setTimeout(function(){ document.write("Displaying after 3 seconds..."); }, 3000); } </script> <p>Wait for 3 seconds after clicking the button</p> </body> </html>

The output displays a button: 

After 3 seconds, the following would be visible since we delayed the execution:

34.

Explain Object.create() in JavaScript?

Answer»

Yes, it is possible to CREATE a custom alert box with CSS and JavaScript library jQuery.

Let us see an example wherein we have styled the alert box, it’s button, background color, border, position, etc.

<!DOCTYPE html> <html>    <head>       <script SRC="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">       </script>       <script>          FUNCTION myAlertBox(msg, myYes) {             var box = $("#test");             box.find(".msg").text(msg);             box.find(".yes").unbind().click(function() {                box.hide();             });             box.find(".yes").click(myYes);             box.show();          }       </script>       <style>          #test {             display: none;             background-color: blue;             border: 2px SOLID #aaa;             color: white;             position: fixed;             width: 250px;             height: 80px;             left: 50%;             margin-left: -80px;             margin-top: 50px;             padding: 10px 10px 10px;             box-sizing: border-box;             text-align: center;          }          #test button {             background-color: white;             display: inline-block;             border-radius: 5px;             border: 1px solid #aaa;             padding: 5px;             text-align: center;             width: 80px;             cursor: pointer;          }          #confirm .msg {             text-align: left;          }       </style>    </head>    <body>       <div id = "test">          <div class = "MESSAGE">Welcome to the website!</div>          <button class  ="yes">OK</button>       </div>       <h2>Fancy Alert Box</h2>       <input type = "button" value = "Display" onclick = "myAlertBox();" />    </body> </html>

The output displays the button which is to be clicked to generate the new custom alert box;

On clicking the above “Display” button, the following alert is visible which we styled: 

35.

Explain Generators in JavaScript?

Answer»

The leading bang! Is USED in anonymous functions:

!FUNCTION(){   // }();

With that, you can also write it as:

+function(){   // }()

Generally, the leading bang (semi-colon) is used in functions in libraries. Let us see the DIFFERENT uses of including a leading semicolon:

Appending

The leading semicolon in immediately-invoked function EXPRESSIONS prevent errors when appending the file during concatenation. This concat is to a file containing an EXPRESSION improperly concluded with a semicolon.

Concatenate

The purpose to include semicolon is to safely concatenate several JS files into one.

Preceding Code

A leading semicolon protects from preceding code, which may have been improperly closed. A semicolon prevents this from occurring. If this is the case, then adding a semicolon will fix it.

Let’s see an example. Let’s say we are concatenating two files with self-invoking functions:

Function ONE

(function(){...ONE...})()

Function TWO 

(function(){...TWO...})()

Now concatenating it will give the following result:

(function(){...ONE...})() (function(){...TWO...})()

Function TWO can have a leading semicolon:

!(function(){...TWO...})()

Now after concatenation: 

(function(){...ONE...})();(function(){...TWO...})()
36.

Explain iterators in JavaScript?

Answer»

The number FORMATTER would allow you to format NUMBERS as the currency you want it to work.

The following is an example for US$ currency. Here we have set the currency as ‘USD’:

<!DOCTYPE html> <html> <BODY> <p>Average cost of a laptop (US$) </p> <script>   var f = new Intl.NumberFormat('en-US', {     style: 'currency',     currency: 'USD',     minimumFractionDigits: 2, }); document.write(f.format(500)); </script> </body> </html>

The output: 

Let us see another example in Euro. Here we have set the currency as ‘EUR’:

<!DOCTYPE html> <html> <body> <p>Average cost of a laptop (US$) </p> <script>   var f = new Intl.NumberFormat('de-DE', {     style: 'currency',     currency: 'EUR',     minimumFractionDigits: 2, }); document.write(f.format(300)); </script> </body> </html>

The output: 

37.

Explain sub-classes and inheritance in ES6?

Answer»

In JavaScript, you may have seen the function name with a leading plus sign:

+function() { }();

The + is used for forcing the parse to consider WHATEVER FOLLOWS the leading plus as expression

This is how you can use + perfectly in a function invoked IMMEDIATELY, for example,

+function() { ALERT("Demo!"); }();

You can also display it as: 

(function() { alert("Demo!"); })();

You can also use it like this (Closing parentheses at the end):

(function() { alert("Demo!"); }());
38.

What are Symbol primitive type in JavaScript?

Answer»

null (var null)

In JavaScript, null is a RESERVED identifier, therefore we cannot use it as an identifier in JavaScript. An error can be seen if we will write:

&LT;html>  <body>    <script>    var null;    </script>  </body> </html>

The following is the error VISIBLE when you will press F12 on browser: 

SYNTAXERROR: Unexpected token null

The web browser throws an error for “var null” since it is a reserved identifier.

UNDEFINED (var undefined)

The undefined is not a reserved identifier, therefore if you will write the following, then no error would be thrown:

<html>  <body>    <script>    var undefined;    document.write(undefined);    </script>  </body> </html>

Even if it is undefined, let us see what would be the output: 

Undefined
39.

What are Set and WeakSet?

Answer»

To understand inheritance using constructor function, we will see an example containing a Mammal parent function and Human child function. Also, make the Human’s Prototype have a reference of Mammal’s Prototype using Object.create. Human’s Prototype will have all methods of Mammal’s Prototype.

 Now, let’s look into “Human” in the console. As you can see it contains “Mammal” sleep and walk function in it’s __proto__.

But we have a major problem because the statement Human.prototype = Object.create(Mammal.prototype) wipes out any Human’s Prototype function and also it’s constructor.

We didn’t declared any Human’s Prototype function, but the constructor was wiped. 

So, we solve it by below code. It is using Human.prototype.constructor = Human to set the constructor back in “Human”.

Also, we are declaring Human’s Prototype function after Human.prototype = Object.create(Mammal.prototype)

... ... Human.prototype = Object.create(Mammal.prototype); Human.prototype.constructor = Human; Human.prototype.fly = function() {   return 'Flying with Gliders'; }

Let’s now complete the code and create two instances of “Human” as hari and harry. Both can access functions walk, sleep and fly.


Interview Tips for Freshers

The INDUSTRY is looking for candidates who can start with their work immediately and not the ones who are looking for a training. As a newbie in the IT Industry for a CAREER as UI DEVELOPER, it’s good to learn the VARIOUS UI frameworks like Vue.JS, React.JS, and Angular.js which are Javascript frameworks. To be shortlisted you can also take up some courses on these front-end technologies.

These javascript interview questions for beginners will help you to crack your javascript interview. Be prepared with the best interview questions for javascript and you will be able to pass the Javascript interview easily. All the best!

40.

What are Map and WeakMap?

Answer»

Prototype chain can be EXPLAINED through below example. Here we have three functions MAMMALWhale and BlueWhale. Each have their own version of print().

We are inheriting from Mammal to Whale by SETTING Whale’s prototype to be Mammal’s prototype.
Then inhering from Whale to BlueWhale by setting BlueWhale’s prototype to be Whale’s prototype.

Then we have three instances of Mammal, Whale and BlueWhale. On calling the print(), we get the RESPECTIVE console log.

Now, let remove BlueWhale’s print() method and then if we call print() on its instance blueWhale, we get result from Whale’s print().

If we further remove Whale’s  print() method and then if we call print() on its instance blueWhale, we get result from Mammal’s print().

So, if you call an method on a Child and the method is not there, it will check in its Parent and if not there then will check in Parent’s parent.

41.

Explain currying in JavaScript and implement multiply(2)(3)(4)(10) using it?

Answer»

 In JavaScript EVERY object is created from a global “Object”(Notice the capital ‘O’). If we look at it in console, it have many properties and create been one of it.

 The Object.create() METHOD creates a new object, using an existing object as the prototype of the newly created object. 

Consider the below example, where we can create a new object from the existing object and can also add new properties to it or modify an existing property.


Now, let see a practical use of Object.create in Inheritance. In below example we have an EMPLOYEE function, which have two functions in its Prototype. Then we have another function SalesEmployee and then set it’s Prototype to Employee’s Prototype. We also have a function in the prototype of SalesEmployee 
SalesEmployee.prototype = Object.create(Employee.prototype);

We then create an INSTANCE of the SalesEmployee as emp1 VARIABLE. It have all functions of Employee function and can also use it.

42.

Implement your version of Array.prototype methods some, every and reduce in vanilla JavaScript ?

Answer»

ES6 introduced a new way of WORKING with functions and iterators in the form of Generators (or generator functions). A generator is a function that can stop midway and then continue from where it stopped.  

Let’s look at the below EXAMPLE. The generator function have a special syntax with “*”. Also, INSIDE the generator we have “yield” statements. Each “next()”, goes to the next yield statement.

The above example doesn’t shows any advantages of generator and it is same as iterating through an array. But let’s look at next example, where we have an infinite while loop inside an generator.
First look at this normal function. If we run it, it will cause an infinite loop and crash your browser.

But the same type of function with generator doesn’t produce an infinite loop. It pauses every time yield is called and will generator the next value of “i” every-time “next()” is called. So, this function can be USED to GENERATE any time “i” and not like in array where we have to give the size of array in advance.

43.

Implement your version of Array.prototype methods forEach, map and filter in vanilla JavaScript ?

Answer»

To understand iterators, we will first LOOK into recently introduced [Symbol.iterator] property in data types. 

This indicates whether a data structure is iterable or not. This includes array, strings, Map, Sets and NodeList. Objects doesn’t have a [Symbol.iterator] property.

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.

Now, iterator are created using the “Symbol.iterator” and can be used to iterate over all data STRUCTURES which have [Symbol.iterator] property.

Let consider the below example. Here we create an iterator by the syntax at line 3. Now we can iterate over the array using “iterator.next()”. Each run gives and OBJECT which have the “value” and “done”, which specifies whether there is an ELEMENT. Notice, after the fifth run we get the “value” as undefined and “done” as true.

44.

Explain nested promises JavaScript?

Answer»

The concept of Sub-classes and inheritance is like that in other languages like Java and C++. The sub-class can inherit properties from its parent class and can also override or update an existing method.

Let’s consider the below example. We have a Parent class “Mammal” and a Sub-class “Bat” which is inheriting from it. Notice, that we have use the “EXTENDS” keyword.
To  use the “legs” and “NAME” variable in “Bat”, we use the “super()” method. Also, notice that we can use update “walk()”, and ADD additional FUNCTIONALITIES.

45.

console.log(('hello').__proto__.__proto__.__proto__);

Answer»

Symbols are the new primitive data-type introduced in ES6. Symbols is unique and immutable data-type. They are tokens that can be used as unique ids.

Two Symbols are NEVER the same, even if they are declared as same. Consider the below example.

We can ALSO put some value inside the constructor in Symbol, which helps in identifying it. Also, it’s typeof is symbol

We cannot directly concatenate it to a Sting as it will throw an error.

So, we CONVERT a Symbol into a String by using string in-built function TOSTRING().

One of the use case of Symbol is to be used as unique keys. We can use them very efficiently in Objects and MAPS, where only unique keys are allowed.

46.

var length = 10; function fn() { console.log(this.length); } var obj = {   length: 5,   method: function(fn) {     fn();     arguments[0]();   } }; obj.method(fn, 1);

Answer»

Map and WeakMap are data structures that were introduced in ES6.

Map is a collection of elements where each ELEMENT is stored as a Key, value pair. Map object can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key,value pair in the same order as inserted.

Let’s find out the reason for Map by analysing a problem with Objects. In the below example, we have an object “x” and another object “a”. Now we are using “a” as a key and push a value to “x”. Now, if we console log “x” the key is shown as [object object], but then also we can extract it’s value by x[a].

But the real problem occurs when we add another object to “x” for key. It over-writes the earlier object. This occurs because in JavaScript we can have only 1 key as an object.

Now we will look at how Maps help. We CREATE Map by the new keyword. And also to add to Map we NEED use one of its method set.
In the below example the objects “a” and “b” are been added as key successfully.

Notice that the __proto__ object contains Symbol.iterator, so the for..of loop can be used to iterate over it like arrays. The same is not true for Objects.

We iterate over Map using the for..of loop. We get an array of [key, value] for each element in Map. So, we de-structure it into [key, value] pair.

If we add the same object as key as in line 9 for “a”, the Map will over-write the OLD value of the key.
Also, we can delete an entry by passing it’s key in delete method.

There is one problem with Map and it is that it holds the Map’s key, even if the original key is deleted. That is the reason we use WeakMap. So, WeakMap allows garbage collector to work as it holds a weak reference to its key but Maps doesn’t allow garbage collector to work.

 Another difference is that keys of WeakMaps are of type Object only. Primitive data types(Number, String, Boolean, Symbol) can only be used in Maps.

47.

What is the issue with the code and how can it be fixed ?

Answer»

We will be implementing some, every and reduce by using of callbacks, in the same way, we used to implement forEach, map and filter in the previous question.

some

The Array prototype method some returns true if any element of the array fulfils the condition we are testing. Here also like filter, we will have the callback been CHECKED in an if statement in every iteration. This will test our condition and even if one of it pass we return a true and get out of LOOP. If the iteration is complete, it means not a single element satisfy condition and we return false.

every

It is the opposite of some. The method “every” will return true only if every element passes the test. Here we do a trick in the if statement. We check the opposite of the test, so say if element should be greater than 10, we are checking for less than 10. So, if even one is less than 10 we return false. And if we iterate through whole loop, means all element satisfy the condition so we return true.

 reduce

The method reduce is considered the hardest in the Array prototype methods to master. It is because it’s concept is quite different. It takes the whole array and iterate through it and returns a single value. It is useful to do sum/multiply/subtract of all the elements of an array, but is more powerful than that. To do this it have an accumulator, which is used to hold the number in each RUN. This accumulator will be operated with the current value of the iteration.
Now in our implementation, we first check whether an accumulator was supplied or ELSE make it to undefined. Now inside the loop we update the accumulator variable by using the callback.

48.

var hero = {     _name: 'Johnny Deep',     getIdentity: function (){         return this._name;     } }; var heroIdentity = hero.getIdentity; console.log(heroIdentity()); console.log(hero.getIdentity());

Answer»

We can implement the Array.prototype methods by using callbacks and actually this is the way it is implemented in JavaScript internally.

forEach

We are implementing our version of forEach as myEach by having the callback attached to the prototype, which is available to every JS function. Here “this” is equal to the array. So, we are iteration over it using traditional for loop and calling the callback function on each iteration.

map

We are implementing our version of map as myMap, by creating an empty array in our function and then pushing it in the iteration. From inside the push we are calling our callback, so when we are calling it we can use SOMETHING like Math.round(line 17) to change an individual item or just return it like in line 13.

filter

We are implementing our version of filter as myFilter. The process is quite similar to map, where we create an empty array ad push to it. But as we KNOW that filter GOES through the array and gives an subset of ELEMENTS depending on BOOLEAN expression.
Here when we iterate through the array and call the callback in an if statement, and if it’s true we are pushing the item into the array.

49.

What is the output of the below code and why?

Answer»

Nested promises are set of promises in which , the result of one promise we call another in the .then statement. It is very USEFUL in practical applications, where the result of fetch from an API endpoint will result in sending the data to another endpoint. Nested promises can also be done with callback functions, but the code get complicated soon.

Let’s look at an example of nested promises. Here we have THREE functions which return promises- movieTicketQueue, buyPopcorn and happyPartner. Now only the movieTicketQueue is returning resolve() or reject() depending on random NUMBER. The other two functions are returning only resolve() for simplicity sake.

Now, when the movieTicketQueue function is run and return a resolve(), then the IMMEDIATE .then block will be run or else we will go to the .catch block. In the .then we are returning the next buyPopcorn and in its .then we are returning the happyPartner. We are passing the message from one function to other, so it will be appended.

On running the code and getting a resolve, because we random number greater than 0.5, we get below output. 

On running the code and getting a reject, because we random number less than 0.5, we get below output.

50.

Tell some practical applications of call, bind and apply?

Answer»

The OUTPUT logged will be: null

The REASON is for PROTOTYPE CHAINING. The __proto__ of ‘hello’ is the global String.

console.log(('hello').__proto__);

Then the __proto__ of it is the global OBJECT.

console.log(('hello').__proto__.__proto__);

Now, the Object is the final thing from which everything in JavaScript is created and it points to null.