Top JavaScript Interview Questions (2019 Edition)

We’ve listed down the top 30 JavaScript interview questions and answers for web developers. After a thorough analysis, we came up with this list. And there is a high probability that you might face similar types of questions during interviews.

JavaScript is cutting-edge technology and remain in high demand. It not only used for creating high-end web applications but also powers many web development frameworks like Angular and Node.js.

In our previous posts, we’d covered a wide range of interviews for web developers especially on HTML5, CSS, JavaScript, Angular, and Node.js. It is worth checking out them if you plan to become a MEAN stack or a full stack web developer.

JavaScript Interview Questions and Answers

Q.1- What’s an object in javascript and how do we create them?

A JavaScript object is an entity having state and behavior (properties and method). Since JavaScript is an object-based language, it treats everything as an object.

JavaScript is a template-based language. It doesn’t need to define a class for creating an object instead creates it directly

JavaScript supports the following three ways to create objects.

1. By object literal.

The syntax of creating an object using object literal is as follows.

object={property1:value1, property2:value2.....propertyN:valueN}

Here, property and value get separated by a colon “:” sign.

Let’s take an example.


std={id:1114, name:"Ram Bajaj", subject:"Physics"} 

document.write(" "" "+std.subject); 


2. By creating an instance of the Object (using new keyword).

The syntax of creating an object:

var objectname=new Object();

Here, the new keyword is used to create the object.

Let’s take an example.


var std=new Object();;"Ram Bajaj"; 


document.write(" "" "+std.subject); 


3. By using an object constructor.

In this method, we create a function with arguments. The value of each of these arguments can be assigned to the current object by using this keyword.

This keyword refers to the current object.

Let’s take an example of creating an object using the object constructor technique.


function std(id,name,subject){;; 



s=new std(1114,"Ram Bajaj","Physics"); 

document.write(" "" "+s.subject); 


Q-2. What does a Scope mean in JavaScript?

The scope determines the accessibility of variables, objects, and functions in particular part of your code.

In JavaScript, the scope is of two types.

1. Global Scope.

A variable defined outside a function comes under the Global scope. Variables defined inside the Global scope are accessible from any part of the code. Let’s see an example.

var name = 'TechBeamers';

console.log(name); // logs 'TechBeamers'

function logName() {

console.log(name); // 'name' is accessible here and everywhere else


logName(); // logs 'TechBeamers'

2. Local Scope.

Variables defined inside a function comes under the Local scope. Different functions can use a variable with the same name. It is because these variables are strictly bound to the function that defines it (each having different scopes) and is not accessible in other functions. Let’s see an example.

// Global Scope

function sampleFunction() {

    // Local Scope #1

    function sample2Function() {

        // Local Scope #2


// Global Scope

function sample3Function() {

    // Local Scope #3


// Global Scope

Q-3. What is <this> in JavaScript?

All the OOPs languages use ‘this’ keyword to refer to an object that is currently instantiated by the class. However, in JavaScript, ‘this’ refers to an object which ‘owns’ the method. Though this varies, with how a function call happens.

Global Scope.

If no object is currently available, then ‘this’ represents the global object. In a web browser, ‘window’ is the top-level object which represents the document, location, history and a few other useful properties and methods. Let’s take a sample code.

window.Obj= "I represent the window object";


alert(this.Obj); // I'm the window object

alert(window === this); // true

The Scenario of a Function Call.

In the case of a function call, ‘this’ refers to the global object.

window.Obj = "I represent the window object";

function TestFunction() {

    alert(this.Obj); // I'm the window object

    alert(window === this); // true



Call Object Methods.

When an object constructor or any of its methods gets called, ‘this’ refers to an instance of an object. It is similar to any class-based language.

window.Obj = "I'm the window object";

function TestFunction() {

    this.Obj = "I'm the Test object";

    this.Verify1 = function() {

        alert(this.Obj); // I'm the Test object



TestFunction.prototype.Verify2 = function() {

    alert(this.Obj); // I'm the Test object


var tf= new TestFunction();



Q-4. 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-5. What is Closure in JavaScript?

A closure is a JavaScript function defined inside another function. And that’s why it gets a special privilege to access three types of scope which are as follows.

  • Internal Scope, i.e., the variables defined between its curly brackets
  • Outer Function Scope, i.e., the variables of the enclosing function
  • Global Scope, i.e., variables defined as globals

Please note that a closure can not only access the outer function variables but also see its parameters. But it can’t call the object of the outer function’s arguments. However, it can directly call the outer function’s parameters.

Here is a code example describing closure by adding a function inside another function.

function outerFunc(arg1, arg2) {

​var param = "I'm closure. ";

// Inner function accessing outer function variables and parameter​s
​function innerFunc() {
​ return arg1 + arg2 + " " + param;
​ ​return innerFunc();


outerFunc("arg1", "arg2");

Q-6. Why is “self” needed instead of “this” in JavaScript?

Inner functions in JavaScript have access to all of the variables defined in the outer function. However, “this” variable is an exception. Since the nested function is just a regular function and not an object method, it’s “this” refers to the global namespace. To make it more clear, let’s look at the following example.

var aProperty = 'global';

var myObject = {

  outerFun: function() {

    this.aProperty = 'local';

    setTimeout(function() {

      console.log(this.aProperty); // outputs 'global'

    }, 1);



Thus, we see that inside “setTimeout” function, “this” refers to the global object. We need a way to get a reference to the object, that is available inside the nested function. We assign the object from “this”, to another(non-special) variable, “self”. It is not a special variable and hence cannot be overwritten by other functions(like “this”). Thus on using “self” inside the inner function, we can refer to the local object. Following is the sample code.

var myObject = {

  outerFun: function() {

    var self = this;

    this.aProperty = 'local';

    setTimeout(function() {

      console.log(self.aProperty); // outputs 'local'

    }, 1);



Q-7. What is an anonymous function and when should you use it?

Anonymous functions are functions that are dynamically declared at runtime. They’re called anonymous functions because they don’t have a name like normal functions.

We use the function operator to declare an anonymous function, instead of the function declaration. Also, the function operator can be used to create a new function, wherever it’s valid to put an expression. For example, we declare a new function to be supplied as an argument to a function call or to assign a property of another object.

Here’s a typical example of a named function.

function testFunction()



Here’s the same example created as an anonymous function.

var testFunction= function()

  alert("Zoom! Zoom! Zoom!");


Following are the key usage of anonymous functions.

  • Code brevity.
    • Use them in
      • Callbacks, and
      • Event handlers.
  • Scope management.
    • They are useful in the following scenario.
      • To create a temporary/private scope.
      • In Closures and Recursions.

Q-8. What is the difference between “==” and “===”?

These are the operators provided by JavaScript – strict equality and Type converting equality.

Strict equality (===) returns true if the values which it is going to compare have the same data type. Taking an example, “2” will not be equal to 2  i.e. (“2″===2) will return false.

Secondly, Type converting equality (==), automatically converts the variable to value irrespective of the data type. Taking an example, here “2” will be equal to 2  i.e. (“2″===2) will return true.

Summarizing it, double equal (==) is an autotype converting equality operator while three equals (===) is a strict equality operator, i.e., it will not convert values automatically.

Q-9. What are JavaScript data types?

JavaScript supports three Primary, two Composite and two Special data types. Next, we list down the data types in each of the categories.

Primary Data Types.

  • String
  • Number
  • Boolean

Composite Data Types.

  • Object
  • Array

Special Data Types.

  • Null
  • Undefined

Q-10. What is prototypal inheritance in JavaScript?

Most of the Object Oriented languages support classes and objects. Here, Classes inherit from other classes.

In JavaScript, the inheritance is prototype-based. It means that there are no classes. Instead, there is an object that inherits from another object.

JavaScript provides three different types of Prototypal Inheritance.

1. Delegation (i.e., the prototype chain).

A delegate prototype is an object that serves as a base for another object. When you inherit from a delegate prototype, the new object gets a reference to the prototype.

When we try to access any property, it first checks in the properties owned by the object. If that property does not exist there, it checks in the ‘[[Prototype]]’ and so on. If that property does not exist there, it checks in the ‘[[Prototype]]’ and so on. Gradually, it moves up the prototype chain, until it reaches the <Object.prototype> i.e., the root delegate for most of the objects.

2. Concatenative Inheritance (i.e. mixins, Object.assign()).

It is the process of inheriting the features of one object to another by copying the source objects properties. JavaScript calls these source prototypes by the name mixins. This process makes use of the JavaScript method Object.assign(). However, before ES6, the <.extend()> method was used.

3. Functional (Not to be confused with functional programming).

In JavaScript, a function can create an object. It’s not necessary to be a constructor(or a class). It is called a factory function. Functional inheritance produces an object from a factory and also extends it, by assigning properties.

Every type of Prototypal Inheritance supports a separate set of use-cases, applicable to it. All of them are equally useful in their ability to enable composition. It provides a has-a, uses-a, or can-do relationship as compared to the is-a relationship created with class inheritance.

Q-11. What is asynchronous programming? Why is it important in JavaScript?

In Asynchronous programming, the engine runs in an event loop. On encountering a blocking operation, a request gets fired, and the code keeps running without blocking for the result. When its execution completes, and the response is ready, it fires an interrupt, which causes an event handler to be run, where the control flow continues. In this way, a single program thread can handle many concurrent operations in asynchronous programming.

The user interface is asynchronous by nature and spends most of the time, waiting for user input to interrupt the event loop and trigger event handlers. Node is asynchronous by default. It means that the server works by waiting for a network request in a loop. Thus, it accepts more incoming requests, while the first one is getting handled.

It is important in JavaScript because it’s suitable for user interface code and beneficial for maintaining the performance on the server.

Q-12. What is variable typing in JavaScript?

JavaScript is very loosely typed language. It means that the variables are declared without a type. Its type is determined once a value is assigned to it. It can change as the variable appears in different contexts.

It’s in contrast to the strongly typed languages that require type declarations.

Consider the following examples.

/* JavaScript Example (loose typing) */ 

var a = 13; // Number declaration 

var b = "thirteen"; // String declaration 

/* Java Example (strong typing) */ 

int a = 13; // int declaration 

String b = "thirteen"; // String declaration

Variable type in JavaScript is determined internally. In the above example, var ‘a’ will be of type ‘Number’ and var ‘b’ will be of type ‘String’.

Q-13. What are the different ways to create an array in JavaScript?

There are two main ways to create an array in JavaScript.

1. Using an array initializer (array literal).

The array initializer (array literal) syntax is simple. It is a comma-separated list of values in square brackets.

Let’s see some examples.

var myArray1 = [1,2,3,4,5]      // an array with 5 elements

var myArray2 = [5]              // an array with 1 element

var myArray3 = [true,'Hi',[7]]  // element types need not be the same.

2. Using the Array constructor.

The Array constructor method has three different syntaxes. If we call the constructor with two or more arguments, it declares an array with array elements also initialized. If we provide only one argument to the Array constructor, it refers to the length of the new array with, elements not initialized. Lastly, the constructor without any argument creates an array with its length set to zero with elements not initialized.

Let’s see some examples.

var myArray4 = new Array(1,2,3,4,5)  // an array with 5 elements

var myArray5 = new Array(20)        // an empty array of length 20

var myArray6 = new Array()           // an empty array of length 0

Q-14. What are JavaScript Cookies?

A cookie is a piece of data which is sent from a website (that owns the requested web page) and gets stored locally by the browser at the user end. Cookies are needed because HTTP protocol which arranges for the transfer of web pages to your browser, is stateless. It means that HTTP has no way to keep track of the activities performed by the user at an earlier point in time. One way to resolve this issue is by using cookies. It contains the following data.

  • A name-value pair containing the actual data
  • An expiry date after which the cookie is no longer valid
  • The domain and path of the server it should be sent to

When a request arrives at the server for a web page that maintains a cookie, the server appends the cookie to the HTTP header to send it across. The server-side programs can then read out the information included in it and decide that you have the right to view the page or not and other user preferences.

Thus, every time you visit the site that maintains the cookies, your information is available there.

Q-15. Which built-in method adds one or more elements to the end of an array and returns the new length of the array?

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Q-16. What is the naming conventions for the variables in JavaScript?

We have to follow the below rules while naming the variables in JavaScript.

  • Do not use any of the JavaScript reserved keywords as a name for your variable. For example, the “break” or “boolean” is the JavaScript keywords, and if used as variable names, it’s invalid.
  • JavaScript variable names should not start with a numeral (0-9). It must begin with a letter or the underscore character. For example, 123var is an invalid variable name, but _123var is a valid one.
  • Also, JavaScript variable names are case sensitive. For example, test and Test are two different variables.

Q-17. How will you create a Cookie using JavaScript?

The simplest way to create a cookie is to assign a string value to the <document.cookie> object.

Its syntax is as follows.

document.cookie = "key1 = value1; key2 = value2; expires = date";

Here, “expires” attribute is optional. We have to provide a date or time value for this attribute.

If we provide a valid value for the date or time, then the cookie will expire at the given date or time, and it will not be accessible after that.

Q-18. How to read a Cookie using JavaScript?

To read a Cookie, we have to access the value of the <document.cookie> object. This <document.cookie> string maintains a list of <name = value> pairs that is separated with semicolons.


"name" is the name of a cookie and

"value" is its string value.

We use String <split()> function to break the <document.cookie> Object to sub-strings. Each of these sub-strings contains a key-value pair which represents the information related to a Cookie.

Q-19. How to delete a Cookie using JavaScript?

To delete a Cookie, we have to set its expiry date to a time that occurred in the past. If attempts are made to read a deleted Cookie then, nothing is returned.

Q-20. How do you submit a form using JavaScript?

We use the following in the web page code to submit a form.


Here <0> refers to the index of the form. If we have more than one forms on a web page, then the index for the first one will be “0”, for the second form, its value will be “1” and so on.

Q-21. Why should you not prefer to use global variables in JavaScript and how can you prevent it?

The principal issue in using a global variable is that someone else can create another variable with the same name. And you may not know it until the duplicate could overwrite the value of your variable.

To avoid using globals, follow any of the following approaches.

1. Create a single global variable that holds all your other variables.

var myGlobalList = {};

myGlobalList.first = "test";

2. Enclose all of your code in a self-executing method/function so that any variable declared inside remain in the function scope.

   var test = "myvar";

Q-22. What are the different objects used in JavaScript?

JavaScript uses a hierarchical structure, applicable to all the objects created in a document. Following are the objects, used in JavaScript that shows the relationship of one object to another.

Window object.

It is the topmost object in the hierarchy. It refers to the content area of the browser window that consists of HTML documents. Each frame is also a window that has some actions inside it.

Document object.

A Document object represents the HTML document that the window will display. It has various properties that refer to other objects, which allow access to and modification of content in the document.

Form object.

A form object is used to take user data as input for processing. It corresponds to an HTML input form constructed with the <FORM>…</FORM> tag.

Q-23. What do we achieve by deferring the loading of JavaScript?

During the page load operation, by default, the parsing of the HTML code remains paused until the execution of the script has not stopped.

Now, if the script is heavy or the server is slow, then this will result in a delay in displaying the web page.

By deferring the loading of JavaScript, we instruct the browser to load the script, only after the loading of the web page(DOM) has finished. It reduces the loading time of the webpage, and it gets displayed faster.

In this way, it makes the page load quicker, without the average user even realizing that some JavaScript load after the DOM has loaded.

Let’s see an example.


    // this piece of code runs first


<script defer="defer">

    //do stuff, but defer it  (runs last)



    //do more stuff (runs second)


Here the middle block will execute once the page has loaded even though it appears before the last block.

Q-24. What is the Strict Mode in JavaScript?

Strict Mode imposes a layer of constraint on JavaScript. It provides the following enhancements.

  • JavaScript will throw an error if we try to use the elements of a deprecated language.
  • To use a variable, it has become mandatory to declare it.
  • It disallows duplicate property and parameter names.
  • The eval() method is safer to use, but still considered evil in some cases.
  • It deprecates the “with” statement.
  • JavaScript will throw an error if we try to assign a value to a read-only property.
  • It decreases the global namespace pollution.

To enable strict mode, we have to add, “use strict” directive to the code. The physical location of the “strict” directive determines its scope. If used at the beginning of the js file, its scope is global. However, if we declare strict mode at the first line in the function block, its scope restricts to that function only.

Q.25- What are event handlers in JavaScript and how to use them?

JavaScript event handlers are functions that bind to a specific HTML DOM event. And events are the part of the HTML document object model (DOM). An event can take place in one of the following cases.

Due to user actions on a web page.

<onclick()>, <onmouseover()>, <onkeydown()>

Some events are callbacks triggered by the browser when a page changes its state.

<onload()>, <onunload()>, <onresize()>

Whenever the DOM receives an event, it calls the JavaScript event handler function bind to the event. To use a handler function, we can assign it to the desired event as an attribute of the target HTML element. Please follow the below example.




<INPUT TYPE=”button” VALUE=”Test” onClick=”window.alert ('Event Handler')”>




Q-26. What does a JavaScript function result when it has no return statement?

If a function doesn’t use the return statement, then it returns undefined as the return value.

However, the browser won’t print anything in its console as it ignores if the expression returns an undefined value. But if we explicitly call such a function inside the console.log() method, then it’ll print exact value.

function test(){}

console.log(test()); // will print 'undefined'

Q-27. What is encodeURI() function?

The encodeURI() function is used to encode a URI. This function encodes all special characters, except these < , / ? : @ & = + $ #>.

Let’s see an example.

var uri="// to make a website using javaScript";

var encodedURI = encodeURI(uri);



We see that JavaScript encodes the space between the words in the <uri> variable as <%20>. Thus, the encodeURI function is used to encode special reserved characters and other non-ASCII characters in the URI.

Q-28. How does the <Array()> differ from <[]> while creating a JavaScript array?

Both the <Array()> and <[]> works almost the same in JavaScript.

If we use them as is (i.e., without any argument) to create an array object, then they will result in an array object of zero length. Also, if we pass a string or a list of strings as arguments, even then the result will be similar.

However, they differ when the input argument is of integer type. In that case, the <Array(n)> statement will create an uninitialized array of size of n. Whereas, the <[n]> statement will create an array of size <1> and assign <n> as value to the first element.

Q-29. How does variable hoisting take place in JavaScript?

In JavaScript, variable declarations are the first piece of code that executes irrespective of their location. Hence, it doesn’t matter whether we declare a variable at the top or anywhere else. This functionality which moves the declaration to the top either inside a function or in the global code is known as hoisting.

out = 2;

var out;

function myfunc() {

   var in = "inside"

   // some code


// ...

JavaScript will interpret the above in the following manner.

var out;

out = 2;

function myfunc() {

    var in;

   // some code

    in = "inside";


Q-30. How will you replace all occurrences of a string in JavaScript?

We can use String’s <replace()> method to substitute any string. There are the following two ways to use this method.

Pass the input string as a regular expression.

str = "ghktestlllltest-sdds"

str = str.replace(/test/g, '');


Use RegExp class to create a regular expression and pass it.

String.prototype.replaceAll = function(find, replace) {

    var target = this;

    return target.replace(new RegExp(find, 'g'), replace);


str = "ghktestlllltest-sdds"

str = str.replaceAll('test', '');


Recommended Posts:

1. 100 AngularJS Interview Questions

2. 30 NodeJS Interview Questions

Summary – Top 30 JavaScript Interview Questions

Web development market is growing from last many years. And with the inception of new technologies like AngularJS/Node.js, it shall expand further. And we are sure that JavaScript would keep its place as the leading skill for web developers.

Also, we wish you can use the above JavaScript interview questions as a quick reference to brush up your skills.