JavaScript Interview Questions and Answers

Q.1.What are the data types supported by JavaScript?
A. The data types supported by JavaScript are:

  • Undefined
  • Null
  • Boolean
  • String
  • Symbol
  • Number
  • Object
Q.2. What are the features of JavaScript?
A. Following are the features of JavaScript:

  • It is a lightweight, interpreted programming language.
  • It is designed for creating network-centric applications.
  • It is an open and cross-platform scripting language.
Q.3.How can you create an object in JavaScript?
A. JavaScript supports Object concept very well. You can create an object using the object literal as follows −
var emp = {
name: "Daniel",
age: 23
Q.4.How can you create an Array in JavaScript?
A. You can define arrays using the array literal as follows-
var x = [];
var y = [1, 2, 3, 4, 5];
Q.5. How to read a cookie using JavaScript?
A. Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie.

  • The document.cookie string will keep a list of name = value pairs separated by semicolons, where name is the name of a cookie and value is its string value.
  • You can use strings split() function to break the string into key and values.
Q.6.What is argument objects in JavaScript & how to get the type of arguments passed to a function?
A. JavaScript variable arguments represents the arguments that are passed to a function. Using typeof operator, we can get the type of arguments passed to a function. For example −
function func(x){
console.log(typeof x, arguments.length);
func(); //==> "undefined", 0
func(7); //==> "number", 7
func("1", "2", "3"); //==> "string", 3
Q.7. How to create a cookie using JavaScript?
A. The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this-
document.cookie = "key1 = value1; key2 = value2; expires = date";
Q.8. What is NaN in JavaScript?
A. NaN is a short form of Not a Number. Since NaN always compares unequal to any number, including NaN, it is usually used to indicate an error condition for a function that should return a valid number. When a string or something else is being converted into a number and that cannot be done, then we get to see NaN.
Q.9. How to delete a cookie using JavaScript?
A. If you want to delete a cookie so that subsequent attempts to read the cookie return nothing, you just need to set the expiration date to a time in the past. You should define the cookie path to ensure that you delete the right cookie. Some browsers will not let you delete a cookie if you don’t specify the path.
Q.10. What is the difference between Local storage & Session storage?

  • Local Storage – The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) – reducing the amount of traffic between client and server. It will stay until it is manually cleared through settings or program.
  • Session Storage – It is similar to local storage ; the only difference is while data stored in local storage has no expiration time, data stored in session storage gets cleared when the page session ends. Session Storage will leave when the browser is closed.
Q.11.What is Closure?
A. Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope. It gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created. To use a closure, simply define a function inside another function and expose it.
Q.12.What will the following code output and why?
var b = 1;
function outer(){
var b = 2
function inner(){
var b = 3;
A.Output to the console will be “3”.There are three closures in the example, each with it’s own var b declaration. When a variable is invoked closures will be checked in order from local to global until an instance is found. Since the inner closure has a b variable of its own, that is what will be output.Furthermore, due to hoisting the code in inner will be interpreted as follows:

function inner () {
var b; // b is undefined
b++; // b is NaN
b = 3; // b is 3
console.log(b); // output "3"
Q.13.Create a function that, given a DOM Element on the page, will visit the element itself and all of its descendents (not just its immediate children). For each element visited, the function should pass that element to a provided callback function.
The arguments to the function should be:

  • a DOM element
  • a callback function (that takes a DOM element as its argument)
A.Visiting all elements in a tree (DOM) is a classic Depth-First-Search algorithm application. Here’s an example solution:

function Traverse(p_element,p_callback) {
var list = p_element.children;
for (var i = 0; i < list.length; i++) {
Traverse(list[i],p_callback); // recursive call
Q.14.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"]

With ES6, one can use the spread operator:

myArray = ['start', ...myArray];
myArray = [...myArray, 'end'];

Or, in short:

myArray = ['start', ...myArray, 'end'];
Q.15. What Is The Prototype Property In JavaScript?
Every JavaScript function has a prototype property (by default this property is null), that is mainly used for implementing inheritance. We add methods and properties to a function’s prototype so that it becomes available to instances of that function. Let’s take an example that calculates the perimeter of a rectangle.

function Rectangle(x, y) {
this.x = x;
this.y = y;
Rectangle.prototype.perimeter = function() {
return 2 * (this.x + this.y);
}var rect = new Rectangle(4, 2);
console.log(rect.perimeter()); // outputs '12'
Q.16. What is an event bubbling in JavaScript?
Event bubbling is a way of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements. The execution starts from that event and goes to its parent element. Then the execution passes to its parent element and so on till the body element.
Q.17. What are Exports & Imports?
Imports and exports help us to write modular JavaScript code. Using Imports and exports we can split our code into multiple files. For example-

//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
export function diag(x, y) {
return sqrt(square(x) + square(y));
//—— main.js ——
{ square, diag } from ‘lib’;
console.log(square(5)); // 25
console.log(diag(4, 3)); // 5
Q.18. What are escape characters in JavaScript?
A. JavaScript escape characters enable you to write special characters without breaking your application. 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.
For example-

document.write "I am a "good" boy"
document.write "I am a \"good\" boy"
Q.19. What is a prompt box in JavaScript?
A. A prompt box is a box which allows the user to enter input by providing a text box. The prompt() method displays a dialog box that prompts the visitor for input. A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering an input value.
Q.20. What is the difference between Call & Apply
A. The call() method calls a function with a given this value and arguments provided individually.
Syntax-[, arg1[, arg2[, ...]]])

The apply() method calls a function with a given this value, and arguments provided as an array.
fun.apply(thisArg, [argsArray])
Q.21. How can you convert the string of any base to integer in JavaScript?
A.The parseInt() function is used to convert numbers between different bases. It takes the string to be converted as its first parameter, and the second parameter is the base of the given string.
For example-

parseInt("4F", 16)
Q.22What is the ‘Strict’ mode in JavaScript and how can it be enabled?
A.Strict mode is a way to introduce better error-checking into your code.

  • When you use strict mode, you cannot use implicitly declared variables, or assign a value to a read-only property, or add a property to an object that is not extensible.
  • You can enable strict mode by adding “use strict” at the beginning of a file, a program, or a function.
Q.23. List some of the advantages of JavaScript.
A. Some of the advantages of JavaScript are:

  • Server interaction is less
  • Feedback to the visitors is immediate
  • Interactivity is high
  • Interfaces are richer
Q.24. List some of the disadvantages of JavaScript.
A. Some of the disadvantages of JavaScript are:

  • No support for multithreading
  • No support for multiprocessing
  • Reading and writing of files is not allowed
  • No support for networking applications.
Q.25. Define anonymous function
A. It is a function that has no name. These functions are declared dynamically at runtime using the function operator instead of the function declaration. The function operator is more flexible than a function declaration. It can be easily used in the place of an expression. For example:

var display=function()
alert("Anonymous Function is invoked");
Q.26. What is DOM? What is the use of document object?
A. DOM stands for Document Object Model. A document object represents the HTML document. It can be used to access and change the content of HTML.
Q.27. What is the use of history object?
A. The history object of a browser can be used to switch to history pages such as back and forward from the current page or another page. There are three methods of history object.

  1. history.back() – It loads the previous page.
  2. history.forward() – It loads the next page.
  3. history.go(number) – The number may be positive for forward, negative for backward. It loads the given page number.
Q.28. How to write a comment in JavaScript?
A. There are two types of comments in JavaScript.

  1. Single Line Comment: It is represented by // (double forward slash)
  2. Multi-Line Comment: Slash represents it with asterisk symbol as /* write comment here */
Q.29. What is the difference between == and ===?
A. The == operator checks equality only whereas === checks equality, and data type, i.e., a value must be of the same type.
Q.31. Difference between Client side JavaScript and Server side JavaScript?
A. Client-side JavaScript comprises the basic language and predefined objects which are relevant to running JavaScript in a browser. The client-side JavaScript is embedded directly by in the HTML pages. The browser interprets this script at runtime.Server-side JavaScript also resembles client-side JavaScript. It has a relevant JavaScript which is to run in a server. The server-side JavaScript are deployed only after compilation.
Q.32. In which location cookies are stored on the hard disk?
A. The storage of cookies on the hard disk depends on the OS and the browser. The Netscape Navigator on Windows uses a cookies.txt file that contains all the cookies. The path is c:\Program Files\Netscape\Users\username\cookies.txt
The Internet Explorer stores the cookies on a file username@website.txt.  The path is: c:\Windows\Cookies\username@Website.txt.
Q.33. Are Java and JavaScript same?
A. No, Java and JavaScript are the two different languages. Java is a robust, secured and object-oriented programming language whereas JavaScript is a client-side scripting language with some limitations.
Q.34. What are the pop-up boxes available in JavaScript?

  • Alert Box
  • Confirm Box
  • Prompt Box
Q.35. How can we detect OS of the client machine using JavaScript?
A. The navigator.appVersion string can be used to detect the operating system on the client machine.
Q.36. What is The Viewport?
A. The viewport is the user’s visible area of a web page.The viewport varies with the device, and will be smaller on a mobile phone than on a computer screen.Before tablets and mobile phones, web pages were designed only for computer screens, and it was common for web pages to have a static design and a fixed size.Then, when we started surfing the internet using tablets and mobile phones, fixed size web pages were too large to fit the viewport. To fix this, browsers on those devices scaled down the entire web page to fit the screen.
Q.37. What is document.write
A. The write() method writes HTML expressions or JavaScript code to a document.The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.