Javascript Interview questions and answers for Experienced

1. JavaScript code to open a URL in new Tab.

In JavaScript we use “”  function to open URL in new Tab.'','_blank');

2. What all Mouse Events in JavaScript

In JavaScript there are 9 mouse events.

  • click: This event is fired when we do a single mouse click.
  • dblclick: This event is fired when we double click with the mouse.
  • mousedown: This event is fired when we click the mouse button down.
  • mouseup: This event is fired when the mouse button is released up.
  • mouseenter: This event is fired when the mouse cursor enters an external element.
  • mouseleave: This event is fired when the mouse cursor leaves an external element.
  • mouseover: This event is fired when the mouse cursor enters an internal and external element.
  • mouseout: This event is fired when the mouse cursor leaves an internal and external element.
  • mousemove: This event is fired when the mouse cursor is moved.

3. What is error object and all error types in JavaScript

Error objects in JavaScript gives information on error throw by JavaScript interpreter.It has two properties

  • Name: Get or set the name of error.
  • Message: Get or set the error message as a string

There are Three error categories in JavaScript

  • Compile Time Errors
  • Logical Errors
  • Run-Time Errors.


try {
  sentmsg("hi there!");
catch(err) {
  console.log( + "\n" + err.message);


sentmsg is not defined

4. What are the different error names from error object

There are six types of errors  often occurred in JavaScript

Error NameDescription
Eval ErrorEval() function throw this error
Range ErrorOut of range” is an error caused by a number
Reference ErrorIt occurs when we use illegal reference
Syntax ErrorIt occurs when we don’t use the syntax correctly
Type ErrorIt is occurred due to a type of error.
URI ErrorencodeURI() throw this error.

5. How we can change the URL of the page in JavaScript without reloading the Page.

We use push state to change the URL of page without reloading it.

window.history.pushState('ABC', 'Page title', '/ABC.php');

6. How to change string in upper-case in JavaScript

In JavaScript toUpperCase() method use to change a string in Upper-Case.

let lowerstr ='Change in Uppercase';
UpperStr = lowerstr.toUpperCase();


7. Program to close window in JavaScript

in Javascript window.close() use to close the window.

<a href='javascript:window.close()'> Close Window </a>

8. How to convert an array in string in JavaScript

join() use to concatenates the array elements in JavaScript with a specified separator between them.

var arrayStr = ["This","is","JavaScript","Array", "Example"];
console.log(arrayStr.join(" "));

//Output :This is JavaScript Array Example

9. Explain is the Temporal Dead Zone

Let and const keywords are introduced in ES6, both give us new ways to declare variables, earlier ES6 we had only var to declare a variable. Let and const declaration is block scope({}) can only be accessed with-in the block({}) of paratheses.

Temporal Dead Zone is behavior that occurs when declaring the variables with let and const keywords, not with var. In ES6 using a let or const before its declaration throw a ReferenceError The time range that happened between creation of variable binding and its declaration is call TDZ.

  var numvar = 15;
  let numlet = 10;


error: Uncaught ReferenceError: Cannot access 'numlet' before initialization

10. What is module in JavaScript and its benefits

Module in JavaScript is a reusable piece of code. So we split the code into multiple files to make code reusable. A module can contain a class or a library of functions to achieve a specific task. Modules use directives export and import to interchange functionality.

Benefits of Modules

  • Maintainability
  • Reusability
  • Namespacing


//msg.js - filename
 export function send(message) {
  console.log(`Hello, ${message}!`);JJ

Let us use above module

//main.js - file name
import {send} from './msg.js';


11. What are Classes in ES6 given example.

A Class keyword introduced in ES6(ES2015), prior to ES6 JavaScript had not class, we often use a constructor function to achieve the same.

function Tree(name) { = name;

Tree.prototype.display = function() {

var apple = new Tree('Apple');

//Output: Apple 

ES6 introduced new syntax to create a class let us understand with example

Here we are using the class keyword instead of function constructor that we use in above example.

class Tree
constructor (name) { = name;

display () 

let apple = new Tree('Apple');


12. What is a service worker

A service worker is a JavaScript script that the browser runs in the background separate from the main browser thread. It does not need user interaction and makes applications work offline if the user lost connection. It intercepts the request and decides what to load.

Features of service worker

  • background sync
  • push notifications
  • commonly used in the offline-first development
  • Rich offline experience
  • Manage a cache of a response programmatically 

13. Explain how to manipulate DOM using a service worker

Service worker does not have direct access to window or document element. A service worker can send messages using client.postMessage() includes a list of DOM elements by (id,class-name,tag-name) to the main thread and the Main thread can perform its task to manipulate DOM.

14.What is web storage in JavaScript and its type

Earlier, HTML 5 application had to store data in cookies.But cookies has some limitations.

Web Storage API provides a mechanism to the web application to store data within the browser locally on the client.

Advantages over cookies

  • Web Storage can use space up to 5MB.
  • Data stores in local storage have no expired date.
  • Web Storage more secure than cookies.

In JavaScript two types of Web Storage

  • Local Storage: It uses window.localStaorage, data store in this available for every does not expire even the browse close or reopens.
  • Session Storage: It stores the data in windows.sessionStorage object for one session. Data is lost if the browser tab will be closed.

15.How do you check browser support web storage

if (typeof(Storage) !== "undefined") {
  // Code here  
else {
  // browser does not support Web Storage..

16 How do you check browser support web workers

if (typeof(Worker) !== "undefined") {
  // Code here  
else {
  // browser does not support Web Storage..

17.What are the restrictions of web workers.

  • web worker can’t access the DOM element.
  • Web workers cannot access JavaScript functions and global objects.
  • Web workers cannot access the alert() and confirm() function.
  • Web workers cannot access the Window object, Document object, the Parent object

18.What is IndexDB in JavaScript

IndexedDB is a new feature in HTML 5 a low-level API for client-side storage and it is more powerful than local-storage used by the application which needs to store large amounts of data.

IndexedDB make us store and retrieve data based on key-values pair.


  • Index DB Store data based on key-values pair.
  • It is not a relational database.
  • IndexedDB API is asynchronous
  • Index DB, not a SQL(structured query language) based

19. What is cookies in JavaScript

Cookies a small amount of data in form of key-value pairs that store in a text file on our computer and accessed by the web browser.

We can access cookies by document.cookie object.

We save our google password so that you do not have to type in the future, in this case, we are using cookies unknowingly.

20. Explain why do we need cookies

In the web application browser communicate with the server using the HTTP protocol, the behavior of HTTP protocol is stateless, but in some situations, we need to maintain the session information on different pages. like login page to send mail or perform other tasks, we need user login information.

  • When a user login on to a website, the user login information stored in a cookie is a text file on our computer
  • Next time the cookie remembers the user login information, it is used by the browser directly from the computer.

21. How to create cookies

We create cookies using the set function in takes two parameter cookies name and its value.

this cookie will delete if user close the web browser.

// create a cookie
Cookies.set('name', 'Rack');

using Expire date property we can set the Expiry date of cookie.

Cookies.set('name', 'Rack', {expiry : new Date(2035, 0, 1)});

22.How to retrieve a cookie.

To retrieve cookies we use the get() function, it takes the cookie name as a parameter. if no cookie found it returns ‘undefined‘.There would be the case that more than one cookie with the same name exists on a different path or Domain. We pass path or Domain name to get specific cookie.

var name =  Cookies.get('name');

To retrieve array of cookies with same name for different path or Domain we pass ‘true’ as second parameter.

//return array of any 'name' cookies
var name =  Cookies.get('name',true);

23. How to delete a cookie in JavaScript.

To delete a cookies we will set the expire date as passed date.

Note: Make sure we pass the cookie path to delete right cookie.

document.cookie = "name=; expires=Wed, 10 Nov 2020 00:00:00 UTC; path=/;";

24. Explain the main difference between localStorage and sessionStorage

The data store in localStorage available for every page, data does not expire even the web browser close or reopens, Whereas data in sessionStorage expire when we close the web browser.

25.How to do access web storage in JavaScript

Window Object has two property localStorage(window.localstorage) and sessionStorage(window.sessionStorage).We use these properties to create instance of Storage object.

//Local storage
//SetItem in local Storage
localStorage.setItem("fruit", 'apple')

//SetItem in local Storage

//Remove data from 

//Remove all data from localStorage


sessionStorage.setItem('fruit', 'apple');

// Get data from sessionStorage
let data = sessionStorage.getItem('fruit');

// Remove data from sessionStorage

// Remove all data from sessionStorage

26.What all methods available in sessionStorage.

In sessionStorage we have methods for writing(Set()),reading(get()),clear().


sessionStorage.setItem('fruit', 'apple');

// Get data from sessionStorage
let data = sessionStorage.getItem('fruit');

// Remove data from sessionStorage

// Remove all data from sessionStorage

27.What is promise in JavaScript

Earlier promise callback functions and events used to perform the asynchronous operation. But they had limited functionalities.

The promise is used in JavaScript to perform the asynchronous operation. It is an object that holds the future value of the asynchronous operation. The promise has the ability to handle multiple asynchronous operations and gives us a better way for error handling ability over callback functions and events.

Promised has three

  • Fulfilled
  • Rejected
  • Pending.


let proms = new Promise(resolve => {
  setTimeout(() => {
    resolve("promise example");
  }, 250);
}, reject => {


proms.then(value => console.log(value));

//Output: promise example

28. Explain why do we need promise.

The promise is used to perform asynchronous operation alternative to callback functions and events , promise reduce the callback hell and make us write the clearner code.

29.What are the Important rules of promise

  • A promise is an object that supplies a standard-compliant .then() method
  • A pending promise may transition into either a fulfilled or rejected state
  • A fulfilled or rejected promise is settled and it must not transition into any other state.
  • Once a promise is settled, the value must not change.

30.What are the three stage of Promise.

  • Fulfilled: This state indicates an operation is successful.
  • Rejected: This stage indicates the specific operation is rejected or an error is thrown.
  • Pending: It is an initial state of the Promise before an operation begins or we can say not yet fulfilled or rejected.