JavaScript Interview Questions and Answers

JavaScript is a popular client-side scripting language that is used in HTML documents mainly for form validation, loading other files and develope any type of client-side application etc. So, the knowledge of javascript is more essential for any web development job. I hope, this article will help the job seekers to prepare them for JavaScript interview.

#01. Write the differences between Java and JavaScript.

JavaScript is a client-side scripting language that is used in web pages.Java is a standard programming language that is used for application development. Java is pure object-oriented programming (OOPS) whereas JavaScript supports some features of OOP.

#02. What are JavaScript Data Types?

JavaScript is a weakly typed language and it does not support datatype declaration like other standard programming languages. JavaScript supports the following data types:

Number
String
Boolean
Object
Array

#03. What is the use of isNaN function?

isNan() function returns true if the argument is not a number otherwise it returns false.

For example:

var s=’Hello’;
if(s.isNaN())
document.write(”string”);
else
document.write(”number”);
Here, isNaN() function will return true and the output will ”string”.

Note:

JavaScript has another function named typeof() to check the data type of a variable.

#04. Is JavaScript faster than ASP script?

JavaScript is faster. JavaScript is a client-side language and thus it does not need any web server. ASP is a server-side language and it is slower than JavaScript. Now, JavaScript is considered as a server-side language when it is used as nodejs.

#05. What is negative infinity?

When a negative number is divided by zero in JavaScript then it is called Negative Infinity.

Example:

document.write(Number.NEGATIVE_INFINITY);

It will return –Infinity.

#06. Is it possible to break JavaScript Code into several lines?

Breaking within a string statement can be done by the use of a backslash, ‘\’, at the end of each line.

Example-1:

document.write(“I like \
programming”);

It will print the text, “I like programming” by ignoring break in the line.

Example-2:

var a=10, b=25,
var c=
a+b;

The above code is correct, but it is not recommended because it hampers debugging.

#07. Which company developed JavaScript?

Netscape developed JavaScript.

#08. What are undeclared and undefined variables?

Undeclared variables are those that do not exist or declared anywhere in a script. If the script tries to read the value of an undeclared variable, then it will return a runtime error.

For example:

var n =10;
alert(x);

Here, the variable, x is not declared and alert() function will generate an error.

The undefined variable is that variable that is declared in the script but no value is assigned to the variable. If the script tries to read the value of an undefined variable, it will return an undefined value.

For example:

var x;
document.write(x);

Here, the variable, x is declared but not defined. The output will be undefined.

#09. Write the code for adding new elements dynamically?

<script>

function insert_ele() {
var nP = document.createElement(“p”);
var tNode = document.createTextNode(” This is a new text node”);
nP.appendChild(tNode); document.getElementById(“fP”).appendChild(nP);
}

</script>

When the function, insert_ele() will be called then it will insert a new paragraph element under the element which id is ‚’fp’ in the document.

#10. What is the global variable? How this variable can be declared and what are the problems associated with it?

The variable is that is accessible throughout all the parts of the script is called a global variable. This type of variable has no scope. The var keyword is used to declare a local variable or object. If the var keyword is omitted, the variable will work as a global variable.

For example:

// Declare a global global

str = “Test”;

The problem of using global variables is the conflict of variable names in the local and global scope. Also, it is difficult to debug and test the code that relies on global variables.

Note:

Local variables are declared within the function and it is not accessible outside the function.

#11. What is a prompt box?

A prompt box is a dialogue box which allows the user to enter input value by providing a text box with label.

For example:

var name=prompt(”What is your name?”,””);

The above script will display a dialog box with a label text, ”What is your name?” and an input textbox. If the user types something and clicks the OK button then the typed value will be stored in the variable name.

#12. What is ‘this’ keyword in JavaScript?

this‘ keyword refers to the object from where it is called.

For Example:

var item = {
Name : “Black Forest Cake”,
Price : 200,
itemFunction : function() {
return this;
}
};

Here, this keyword refers the object item.

Note:

Two main part of object-oriented programming is class and object and an object is an instance of a class.

#13. Explain the working of timers in JavaScript? Also elucidate the drawbacks of using the timer, if any?

Timers are used to execute a piece of code at a set time or it is used also to repeat the code in a given interval of time. This is done by using the functions setTimeout, setInterval and clearInterval.

The setTimeout(function, delay) function is used to start a timer that calls a particular function after the mentioned delay. The setInterval(function, delay) function is used to repeatedly execute the given function in the mentioned delay and only halts when canceled. The clearInterval(id) function instructs the timer to stop. Timers are operated within a single thread, and thus events might queue up and waiting to be executed.

#14. Which symbol is used for comments in Javascript?

// and /* – – */ are used to define comments in javascript code.

For Example:

// For Single line comments

/* Multi

Line

Comment

*/

#15. What is the difference between ViewState and SessionState?

ViewState‘ contains page specific data in a session.

SessionState‘ contains user-specific data that can be accessed across all pages in the web application.

#16. What is === operator?

=== is called a strict equality operator that returns true when the two operands contain the same value and data type.

For Example:

var n=”50″
if(n===50)
alert(“Values are equal”);
else
alert(“Values ar not equal”);
The above script will show the alert with the value, ”Values are not equal” because “50” is a string and 50 is number.

Note:

“==” is also an equality operator but it compares the values of the operands but not the datatypes.

#17. Explain how can you submit a form using JavaScript?

To submit a form using JavaScript use document.form[0].submit(). If the HTML script contains multiple forms then it will submit the first form data only. Another way to submit a form is to use the submit button as a form element.

#18. Does JavaScript support automatic type conversion?

Yes, JavaScript supports automatic type conversion and it is the common way of type conversion used by JavaScript developers.

For example:

var myVar=520;
myVar=’Javascript Programming’;

Here, the variable, myVar contains number data at the time of declaration and data type is a number for the first statement. In the second statement, the data type is automatically changed to string for assigning string value in myVar.

#19. Explain how to read and write a file using JavaScript?

There are two ways to read and write a file using JavaScript

Using JavaScript extensions
Using a web page and Active X objects

#20. What types of loops are supported by JavaScript?

Javascript loops:

For
While
do-while loops

For example:

//For loop example

for (var i = 0; i < arr.length; i++) {
str += arr[i] + ” “;
}

Here, arr array is iterated by using for loop and array values are stored in the variable str by separating space.

//While loop example

var i=0;
while (i < 5) {
document.write(“The current value of i= ” + i);
i++;
}

While loop will iterate 5 times and print the value of each iteration.

//do-while loop example

var i = 10;
do {
document.write(“The current value of i= ” + i);
i–;
}

while (i > 0);

do-while loop will iterate for 10 times and print the value of each iteration.

#21. 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.

Example:

To convert 4F (of base 16) to an integer, the code used will be -parseInt (“4F”, 16);

Note:

JavaScript has another built-in function, parseFloat() to convert any string data to floating numbers.

#22. Explain the difference between “==” and “===”?

“==” checks only for equality of values in the variables. “===” checks the equality of values and data types in the variables and it returns false if either the value or the type of the two variables are different.

#23. 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.

#24. Explain how to detect the operating system on the client machine?

navigator.platform property can be used to detect the operating system.

#25. What do you mean by NULL in Javascript?

The NULL value is used to represent no value or no object.

Example:

var data = NULL;

#26. What is the function of the delete operator?

The delete keyword is used to delete the property as well as its value.

Example

var customer= {age:20, batch:”ABC”};
delete customer.age;

#27. What Pop up dialogue boxes are available in JavaScript?

Alert
Confirm and
Prompt

Example:

//alert example

alert(“Learn javascript”);

//confirm example

confirm(“Do you want to delete?”);

//prompt example

prompt(“Enter the value of n”,0);

Note:

A prompt box is used to take input from the user, an alert box is used to provide necessary information for the user and confirm box is used to confirm or cancel any task.

#28. What is the use of void(0)?

It is used to prevent the page from refreshing and the parameter “zero” is passed while calling.
It is used to call another method without refreshing the page.

#29. How can a page be forced to load another page in JavaScript?

location.href property can be used to force a page to load another page.

Example:

<script language=”JavaScript” type=”text/javascript” >

location.href=”http://localhost/mypath/myfile.html”;

</script>

#30. What is the data type of variables of in JavaScript?

All variables in JavaScript are object data types.

#31. What is the difference between an alert box and a confirmation box?

An alert box displays only one button which is the OK button. But a Confirmation box displays two buttons namely OK and cancel.

#32. 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.

Example:

document.write( “I m a “good” girl”);
document.write (“I m a \”good\” girl”)

Here, backslash(\) is used to print double quotes inside a text.

#33. What are JavaScript Cookies?

Cookies are the small text files stored in the visiter’s computer and it creates when the user visits the websites and it stores the information that the user needs. For example, User name and shopping cart information can be stored in the cookie from the previous visits.

#34. What is the function of pop() method in JavaScript?

The pop() method is similar to the shift() method but the difference is that the shift() method works at the start of the array and the pop() method works at the beginning of the array. It is used to retrieve data from the array.

Example:

var dresses = [“Shirt”, “Pant”, “TShirt”];
dresses.pop();

After executing the above code dresses array will contain only Shirt and Pant.

Note:

The opposite function of pop() is push() that is used to insert data at the beginning of the array.

#35. Is JavaScript has concept level scope?

No. JavaScript does not have a concept level scope. The variable declared inside the function has scope inside the function.

#36. Mention what are the disadvantages of using innerHTML in JavaScript?

The disadvantages of innerHTML in JavaScript are,

The content can’t be appended by this method. So, the new content always overwrites the old content.

The entire innerHTML content is re-parsed and build into elements, therefore its much slower.

#37. What is break and continue statements?

Break statement exits from the current loop and Continue statement continues with the next statement of the loop.

For example:

//break example

for(var i=0; i <10; i++)
{
If(i==5) break;
document.write(i);
}

The loop will terminate when the value of i is 5.

//continue example

for(var i=10; i >0; i–)
{
If(i==6) continue;
document.write(i*2);
}

When the value of i is 6 then the loop will continue without executing the statement document.write(i*2).

#38. What are the two basic groups of data types in JavaScript?

Two main groups of data types in JavaScript are:

  • Primitive
  • Compound

Primitive data types are number, string, and Boolean that can store a single value. Compound data types can store more than one value in a variable, such as Array, Object, Date, etc.

#39. How generic objects can be created?

Generic objects can be created as:

var i = new object();

#40. What is the use of the type of operator?

‘Typeof’ operator is used to return a string description of variable type.

For example:

If(typeof 37 === ‘number’)
alert(‘equal’);
else
alert(’not equal’);

Here, the typeof operator will return number and the text‚ equal will be printed in the alert box.

#41. Which keywords are used to handle exceptions?

Try…Catch…finally, the block is used to handle exceptions in JavaScript.

Try{
Main code
}

Catch(exp){
Throw an exception if any error occurs in the try block
}

Finally{
Code runs either it finishes successfully or after catching any error
}

#42. Which function is used to print the text on the screen?

document.write(“string”) is used to print the text on the screen.

#43. What is the use of the blur function?

Blur function is used to remove the focus from the specified object.

Example:

document.getElementById(”eleName”).blur();

#44. What are the different types of errors in JavaScript?

There are three types of errors in JavaScript:

  • Load time errors: Errors like syntax errors are known as Load time errors and it generates the errors dynamically.
  • Run time errors: Errors that come due to the misuse of the command inside the script is known as run time errors.
  • Logical Errors: These are the errors that occur due to the illogical operation on a function or script.

#45. 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.

For example:

var book = [“PHP”, “ASP”, “Java”, “C#”];

book.push(“C++”);

New element ”C++” will be added at the end of the array book.

#46. What is the unshift method in JavaScript?

Unshift method is like the push method which works at the beginning of the array. This method is used to prepend one or more elements to the beginning of the array.

For example:

var book = [“PHP”, “ASP”, “Java”, “C#”];

book.unshift(“VB.Net”);

The new element “VB.Net” will be added at the beginning of the array book.

#47. What is the difference between JavaScript and Jscript?

Both are almost similar. JavaScript is developed by Netscape and Jscript was developed by Microsoft.

#48. How are object properties assigned?

Properties are assigned to objects in the following way –

obj[“class”] = 12;
or
obj.class = 12;

#49. What is the way to get the status of a CheckBox?

The status can be acquired as follows –

alert(document.getElementById(‘checkbox1’).checked);

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

#50. 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.

#51. How can a value be appended to an array?

A value can be appended to an array in the given manner –

arr[arr.length] = value;

#52. 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
}

In each repetition, one property from the object is associated with the variable name, and the loop is continued till all the properties of the object are iterated.

For example:

var marks = {10987:78, 56342:89, 78456:92};
var val;
for (id in marks) {
document.write(”The marks obtained by „+ id+” is ”+ marks[id]+”<br/>”);
}

Here, for-in loop is used to iterate the array marks print each value with index in each line.

#53. 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.

For Example:

var anony = function() {
alert(‘I am anonymous function’);
};

anony();

#54. Is JavaScript case sensitive? Give an example?

Yes, JavaScript is case sensitive. For example, a function parseInt is not the same as the function Parseint.

#55. What boolean operators can be used in JavaScript?

The ‘And’ Operator (&&), ‘Or’ Operator (||) and the ‘Not’ Operator (!) can be used in JavaScript.

Example:

if(n<10 && n>99)
alert(“Invalid data”);

You can check the following article for css interview questions and answers.

CSS interview questions and answers