JavaScript interview questions and answers | Infographic

Basic and most common JavaScript interview questions and answers.

Question 1: What is closure in JavaScript?

Answer: A closure is a funciton and has access to variables that are declared and defined in the parent function scope even after the outer function has returned.

function init() {
  var name = 'Mozilla'; // name is a local variable created by init
  function displayName() { // displayName() is the inner function, a closure
    alert(name); // use variable declared in the parent function
  }
  displayName();
}
init();

Question 2: What is the use of window objects in JavaScript?

Answer: The window object is created automatically by the browser that represents the window of a browser. It is a browser object, not a JavaScript Object.

Methods of the window object:

MethodDescription
alert()displays the alert box containing a message with the ok button.
confirm()displays the confirm dialog box containing messages with the ok and cancel buttons.
prompt()displays a dialog box to get input from the user.
open()opens the new window.
close()closes the current window.
setTimeout()performs an action after a specified time like calling function, evaluating expressions, etc.

Question 3: What is the use of the History object in JavaScript?

Answer: A History object of the browser is used to roll back the previous user history and actions. Such as Back and forward from a current web page or another page.

MethodsDescription
back()specifies a method that loads the previous URL from the history list.
forward()specifies a method that loads the next URL from the history list.
go()specifies a method that loads a specific URL from the history list.
pushState()used to push the given data onto the session history stack with the specified title
replaceState()used to update the most recent entry on the history stack to the specified data, title, and, if provided, URL

Question 3: What is difference between == and ===?

Answer:

  • = is used for assigning values to a variable in JavaScript.
  • == is used for comparison between two variables irrespective of the datatype of variable.
  • === is used for comparision between two variables but this will check strict type, which means it will check datatype and compare two values.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.