javascript-interview-questions (Part- 1)

Javascript interview questions (Part- 2)

What is JavaScript?
The JavaScript is most popular scripting languages and it developed by Netscape and used to develop the client side web applications.

What are undeclared and undefined variables?
Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.

Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.

Write the code for adding new elements dynamically?

<head> <title>t1</title>
<script type="text/javascript">
function addNode() { var newP = document.createElement("p");
var textNode = document.createTextNode(" This is a new text node");
newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); }
</script> </head>
<body> <p id="firstP">firstP<p> </body>

Explain how can you submit a form using JavaScript?
To submit a form using JavaScript use document.form[0].submit();

Does JavaScript support automatic type conversion?
Yes JavaScript does support automatic type conversion, it is the common way of type conversion used by JavaScript developers

How can the style/class of an element be changed?

It can be done in the following way:
document.getElementById(myText).style.fontSize = 20?;
document.getElementById(myText).className = anyclass;

How can you convert the string of any base to integer in JavaScript?

The parseInt() function is used to convert numbers between different bases. parseInt() takes the string to be converted as its first parameter, and the second parameter is the base of the given string.

In order to convert 4F (of base 16) to integer, the code used will be –
parseInt ("4F", 16);

 What would be the result of 3+2+”7″?
Since 3 and 2 are integers, they will be added numerically. And since 7 is a string, its concatenation will be done. So the result would be 57.

What do mean by NULL in Javascript?
The NULL value is used to represent no value or no object.  It implies no object or null string, no valid boolean value, no number and no array object.

What are all the types of Pop up boxes available in JavaScript?

Confirm and

What is the use of Void(0)?
Void(0) is used to prevent the page from refreshing and parameter “zero” is passed while calling.
Void(0) is used to call another method without refreshing the page.

What is the data type of variables of in JavaScript?
All variables in the JavaScript are object data types.

What are escape characters?
Escape characters (Backslash) is used when working with special characters like single quotes, double quotes, apostrophes and ampersands. Place backslash before the characters to make it display.


document.write "I m a "good" boy"
document.write "I m a \"good\" boy"

What are JavaScript Cookies?
Cookies are the small test files stored in a computer and it gets created when the user visits the websites to store information that they need. Example could be User Name details and shopping cart information from the previous visits.

What is break and continue statements?
Break statement exits from the current loop.
Continue statement continues with next statement of the loop.

What are the two basic groups of dataypes in JavaScript?
They are as –

Reference types.

Primitive types are number and Boolean data types.
Reference types are more complex types like strings and dates.

Which keywords are used to handle exceptions?
Try… Catch—finally is used to handle exceptions in the JavaScript

Code to throw an exception
Code runs either it finishes successfully or after catch

Which keyword is used to print the text in the screen?
document.write(“Welcome”) is used to print the text – Welcome in the screen.

What is the use of Push method in JavaScript?
The push method is used to add or append one or more elements to the end of an Array. Using this method, we can append multiple elements by passing multiple arguments

What is the difference between JavaScript and Jscript?
Both are almost similar. JavaScript is developed by Netscape and Jscript was developed by Microsoft 

What is the ‘Strict’ mode in JavaScript and how can it be enabled?
Strict Mode adds certain compulsions to JavaScript. Under the strict mode, JavaScript shows errors for a piece of codes, which did not show an error before, but might be problematic and potentially unsafe. Strict mode also solves some mistakes that hamper the JavaScript engines to work efficiently.

Strict mode can be enabled by adding the string literal “use strict” above the file. This can be illustrated by the given example:

function myfunction()
use strict";
var v = “This is a strict mode function";

 What is the way to get the status of a CheckBox?
The status can be acquired as follows –

If the CheckBox will be checked, this alert will return TRUE.

Explain window.onload and onDocumentReady?
The onload function is not run until all the information on the page is loaded. This leads to a substantial delay before any code is executed.

onDocumentReady loads the code just after the DOM is loaded. This allows early manipulation of the code.

Explain the for-in loop?
The for-in loop is used to loop through the properties of an object.
The syntax for the for-in loop is –

for (variable name in object){
statement or block to execute

 Describe the properties of an anonymous function in JavaScript?
A function that is declared without any named identifier is known as an anonymous function. In general, an anonymous function is inaccessible after its declaration.

Anonymous function declaration –
var anon = function() {
alert('I am anonymous');

How are object properties assigned?
Assigning properties to objects is done in the same way as a value is assigned to a variable.
For example, a form object’s action value is assigned as ‘submit’ in the following manner – Document.form.action=”submit”

What is the role of break and continue statements?
Break statement is used to come out of the current loop while the continue statement continues the current loop with a new recurrence.

Example of terminating a loop using break
  1. <script>  
  2.     for (i = 0; i < 20; i++) {  
  3.         if (i >= 5) {  
  4.             break;  
  5.         }  
  6.         document.write("Pass index " + i + " of the loop<br />");  
  7.     }  
  8. </script>  

JavaScript continue statement 
JavaScript continue statement is used to bypass the specified iterations of a loop, so that the code in the loop statement does not execute for the specified iterations and moves on to the next.
  1. <script>  
  2.     for (i = 0; i < 20; i++) {  
  3.         if (i < 10) {  
  4.             continue;  
  5.         }  
  6.         document.write("Pass index " + i + " of the loop<br />");  
  7.     }  
  8. </script>  

Explain Arrays in JavaScript.
 An array is a collection of the similar data types. All its values are stored in the index locations, which start in the range 0 to n-1.

Declaration of an Array
  1. var myArray = [];  
  2. var myArray = [value1, value2, value3, so on...];  
  3. var myArray = new myArray(length_of_array);  
Let's understand this with the following examples.


  1. var myArray = [20, 30, 40, 50];  
  2. for (var i = 0; i <= myArray.length - 1; i++) {  
  3.     document.write("The value at the index location " + i + " is " + myArray[i] + " <br/>");  
  4. }  
The preceding code declares an array with 4 values. The for loop is used, which starts the index value "i" from 0 until the length of "myArray" and the index location is incremented by 1.

Exception Handling in JavaScript.
This is a new feature of JavaScript for handling the exceptions like in other programming languages, using try catch finally statements and the throw operator for handling the exceptions. Now, you can catch the runtime exception.
The following example shows an exception handling:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <title>Article By Jeetendra</title>  
  5. <head> </head>  
  7. <body>  
  8.     <script type="text/javascript">  
  9.         document.write("Exception Handling in JavaScript</br>");  
  11.         function ExceptHand() {  
  12.             try {  
  13.                 alert("This is try block");  
  14.                 alert("Not present");  
  15.             } catch (error) {  
  16.                 document.write(error);  
  17.             }  
  18.         }  
  19.         ExceptHand();  
  20.     </script>  
  21. </body>  
  23. </html>  
Closure in JavaScript
Basically a closure is a local variable, which will be executed after the specific function has returned. A Closure provides us a free environment, where the outer function can easily access the inner functions and inner variables without any scope restrictions.

  1. <html>    
  2. <head>  
  3.     <script type="text/javascript" language="JavaScript">  
  4.         function ExClosure(a, ref1) {  
  5.             var v1 = a;  
  6.             var ref = ref1;  
  7.             return function(v2) {  
  8.                 v1 += v2;  
  9.                 alert("Add:" + v1)  
  10.                 alert("Reference Value:" +;  
  11.             }  
  12.         }  
  13.         myclosure = ExClosure(10, {  
  14.             cv: 'My First Closure'  
  15.         });  
  16.         myclosure(5);  
  17.     </script>  
  18. </head>  
  20. <body onload="ExClosure(b,ref)"> </body>  
  21. </html>  
In this example, when the ExClosure function is called, it returns a function. The function remembers the value of a (10) in the form of v1, it means the myclosure will add 10 together with 5 and return 15 as an alert and the next alert returns the Reference value (Reference Value: My First Closure).

Math Object In JavaScript.
JavaScript also provides “Math” object to perform mathematical operations. Math object has properties and methods, which helps to perform the mathematical tasks. Math object is not a constructor. All the methods and properties of Math are static, so they can be accessed, using Math as an object without creating one.

Math Methods
Math object provides the following methods for the mathematical operations.
  • abs():
  • acos():
  • asin():
  • cos():
  • tan():
  • sin():
  • ceil():
  • floor():
  • max():
  • min():
  • exp():
  • log():
  • pow():
  • random ():
  • round ():
  • sqrt ():
Chaining in JavaScript.
This technique got / retrieved popularity from jQuery. We write the series of statements, one after the other like a chain. 

  1. $("#h1").text("Change text").css("color""red");   

What are Screen objects?
Screen objects are used to read the information from the client’s screen. The properties of screen objects are –

AvalHeight: Gives the height of client’s screen
AvailWidth: Gives the width of client’s screen.
ColorDepth: Gives the bit depth of images on the client’s screen
Height: Gives the total height of the client’s screen, including the taskbar
Width: Gives the total width of the client’s screen, including the taskbar

Define unescape() and escape() functions?
The escape () function is responsible for coding a string so as to make the transfer of the information from one computer to the other, across a network.

For Example:
document.write(escape(Hello? How are you!));

Output: Hello%3F%20How%20are%20you%21

The unescape() function is very important as it decodes the coded string.

It works in the following way.
For example:


Output: Hello? How are you!

What are the decodeURI() and encodeURI()?
EncodeURl() is used to convert URL into their hex coding. And DecodeURI() is used to convert the encoded URL back to normal.

var uri="my test.asp?name=ståle&car=saab";
document.write(encodeURI(uri)+ "<br>");

Output –
my test.asp?name=ståle&car=saab

What does the following statement declares?
var myArray = [[[]]];

It declares a three dimensional array.

Get all visible DIVs on a page with javascript?
It's easy with jQuery...

But if you want to be old school...
var divs = document.getElementsByTagName("DIV");
var elems = [];

for(var i = 0; i < divs.length; i++) {
  var div = divs[i];
  var vis =;

  if(vis == 'block' || vis == 'inline')

What is prototype in javascript ?

The prototype property allows you to add properties and methods to an object.

    function person(first, last, age, eye) {
        this.firstName = first;
        this.lastName = last;
        this.age = age;
        this.eyeColor = eye;
    person.prototype.nationality = "English";

    var myFather = new person("John""Doe", 50, "blue");
    document.getElementById("demo").innerHTML =
    "My father is " + myFather.nationality;


JSON.parse(): The JSON.parse() method parses a string as JSON

JSON parse example - Object From String
Create a JavaScript string containing JSON syntax:
var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

The JavaScript function JSON.parse(text) can be used to convert a JSON text into a JavaScript object:

var obj = JSON.parse(text);

Use the new JavaScript object in your page:


<p id="demo"></p>

    document.getElementById("demo").innerHTML =
    obj.employees[1].firstName + " " + obj.employees[1].lastName;

The JSON.stringify() method converts a JavaScript value to a JSON string.

JavaScript Prototype
Every JavaScript object has a prototype. The prototype is also an object.
All JavaScript objects inherit their properties and methods from their prototype.

Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to). However, the outer function does not have access to the variables and functions defined inside the inner function. 

What will the code below output to the console and why ?

console.log(1 +  "2" + "2");
console.log(1 +  +"2" + "2");
console.log(1 +  -"1" + "2");
console.log(+"1" +  "1" + "2");
console.log( "A" - "B" + "2");
console.log( "A" - "B" + 2);

The above code will output the following to the console:
Here’s why…
The fundamental issue here is that JavaScript (ECMAScript) is a loosely typed language and it performs automatic type conversion on values to accommodate the operation being performed. Let’s see how this plays out with each of the above examples.

Example 1: 1 + "2" + "2" Outputs: "122" Explanation: The first operation to be performed in 1 + "2". Since one of the operands ("2") is a string, JavaScript assumes it needs to perform string concatenation and therefore converts the type of 1 to "1"1 + "2" yields "12". Then, "12" + "2" yields "122".
Example 2: 1 + +"2" + "2" Outputs: "32" Explanation: Based on order of operations, the first operation to be performed is +"2"(the extra + before the first "2" is treated as a unary operator). Thus, JavaScript converts the type of "2" to numeric and then applies the unary + sign to it (i.e., treats it as a positive number). As a result, the next operation is now 1 + 2 which of course yields 3. But then, we have an operation between a number and a string (i.e., 3 and "2"), so once again JavaScript converts the type of the numeric value to a string and performs string concatenation, yielding "32".
Example 3: 1 + -"1" + "2" Outputs: "02" Explanation: The explanation here is identical to the prior example, except the unary operator is - rather than +. So "1" becomes 1, which then becomes -1 when the - is applied, which is then added to 1yielding 0, which is then converted to a string and concatenated with the final "2" operand, yielding "02".
Example 4: +"1" + "1" + "2" Outputs: "112" Explanation: Although the first "1" operand is typecast to a numeric value based on the unary + operator that precedes it, it is then immediately converted back to a string when it is concatenated with the second "1" operand, which is then concatenated with the final "2" operand, yielding the string "112".
Example 5: "A" - "B" + "2" Outputs: "NaN2" Explanation: Since the - operator can not be applied to strings, and since neither "A" nor "B" can be converted to numeric values, "A" - "B" yields NaN which is then concatenated with the string "2" to yield “NaN2”.
Example 6: "A" - "B" + 2 Outputs: NaN Explanation: As exlained in the previous example, "A" - "B" yields NaN. But any operator applied to NaN with any other numeric operand will still yield NaN.

What will be the output when the following code is executed? Explain.

console.log(false == '0')
console.log(false === '0')

The code will output:
In JavaScript, there are two sets of equality operators. The triple-equal operator === behaves like any traditional equality operator would: evaluates to true if the two expressions on either of its sides have the same type and the same value. The double-equal operator, however, tries to coerce the values before comparing them. It is therefore generally good practice to use the === rather than ==. The same holds true for !== vs !=.

What will be the output of this code?
var x = 21;
var girl = function () {
    var x = 20;
girl ();

Neither 21, nor 20, the result is undefined
It’s because JavaScript initialization is not hoisted.
(Why doesn’t it show the global value of 21? The reason is that when the function is executed, it checks that there’s a local xvariable present but doesn’t yet declare it, so it won’t look for global one.)

What do the following lines output, and why?
console.log(1 < 2 < 3);
console.log(3 > 2 > 1);

The first statement returns true which is as expected.
The second returns false because of how the engine works regarding operator associativity for < and >.
It compares left to right, so 3 > 2 > 1 JavaScript translates to true > 1true has value 1, so it then compares 1 > 1, which is false.
How do you add an element at the begining of an array? How do you add one at the end?
var myArray = ['a', 'b', 'c', 'd'];
console.log(myArray); // ["start", "a", "b", "c", "d", "end"]
Imagine you have this code:

var a = [1, 2, 3];
1) Will this result in a crash?
     a[10] = 99;

2) What will this output?

1) It will not crash. The JavaScript engine will make array slots 3 through 9 be “empty slots.”
2) Here, a[6] will output undefined, but the slot still remains empty rather than filled with undefined. This may be an important nuance in some cases. For example, when using map(), empty slots will remain empty in map()’s output, but undefined slots will be remapped using the function passed to it:
var b = [undefined];
b[2] = 1;
console.log(b);             // (3) [undefined, empty × 1, 1]
console.log( => 7)); // (3) [7,         empty × 1, 7]

What would following code return?
console.log(typeof typeof 1);

Answer:   string
typeof 1 will return "number" and typeof "number" will return string.

What is the difference between undefined and not defined in JavaScript?
In JavaScript, if you try to use a variable that doesn't exist and has not been declared, then JavaScript will throw an error var name is not defined and script will stop executing.

Let's say var x is a declaration because you have not defined what value it holds yet, but you have declared its existence and the need for memory allocation.

var x; // declaring x console.log(x); //output: un

If a variable that is neither declared nor defined, when we try to reference such a variable we'd get the result not defined.
console.log(y); // Output: ReferenceError: y is not defined

Write a mul function which will produce the following outputs when invoked:
console.log(mul(2)(3)(4)); // output : 24 console.log(mul(4)(3)(4)); // output : 48
Below is the answer followed by an explanation to how it works:
function mul (x) { return function (y) { // anonymous function return function (z) { // anonymous function return x * y * z; }; }; }

Here the mul function accepts the first argument and returns an anonymous function, which takes the second parameter and returns another anonymous function that will take the third parameter and return the multiplication of the arguments that have been passed.
In JavaScript, a function defined inside another one has access to the outer function's variables. Therefore, a function is a first-class object that can be returned by other functions as well and be passed as an argument in another function.
  • A function is an instance of the Object type
  • A function can have properties and has a link back to its constructor method
  • A function can be stored as a variable
  • A function can be pass as a parameter to another function
  • A function can be returned from another function
How can we empty the array below?
var arrayList = ['a','b','c','d','e','f'];

1- arrayList = []
2- arrayList.length = 0;
3- arrayList.splice(0, arrayList.length);
while(arrayList.length){ arrayList.pop(); }

What will be the output of the code below?
var trees = ["xyz","xxxx","test","ryan","apple"]; delete trees[3]; console.log(trees.length);

The output would be 5. When we use the delete operator to delete an array element, the array length is not affected from this. This holds even if you deleted all elements of an array using the delete operator.

What will be the output of the code below?
var bar = true; console.log(bar + 0); console.log(bar + "xyz"); console.log(bar + true); console.log(bar + false);

The code will output 1, "truexyz", 2, 1. Here's a general guideline for addition operators:

Number + Number -> Addition
Boolean + Number -> Addition
Boolean + Number -> Addition
Number + String -> Concatenation
String + Boolean -> Concatenation
String + String -> Concatenation


Post a Comment


ADFS (1) ADO .Net (2) Ajax (1) Angular (1) Angular Js (17) Angular2 (28) ASP .Net (14) Authentication (1) Azure (1) Breeze.js (1) C# (50) CD (1) CI (2) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DevOps (4) DI (4) Dotnet (22) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (8) Lamda (3) Linq (11) Mongodb (1) MVC (50) NodeJS (7) RDLC (1) Report (1) SDLC (1) Sql Server (30) SSIS (3) SSO (1) SSRS (2) UI (1) WCF (13) Web Api (11) Web Service (1) XMl (1)