We are Hiring Tech Content Writers (Freelancer/Full-Time). Are you interested? Apply Now

20 Important JavaScript Interview Questions with Answers

JavaScript Interview Questions


Spread the love

JavaScript is the popular programming language of the web. The high-level, interpreted programming language follows a multi-paradigm approach. As such, it has several traits of functional programming.

If you take a look at the Stackoverflow Developer Survey 2018, you will find that JavaScript tops the list of the most preferred programming language for the 6th consecutive year.

Almost 70% of all the respondents of the Stackoverflow survey state that they have been using JS for their day-to-day development chores. Hence, following a career path in JavaScript development is lucrative.

JavaScript Interview Questions

Here we have compiled a list of 20 important JS interview questions that will help you seize that upcoming JS interview.

Q: Can you differentiate between let and var?
A: Both let and var are used for variable and method declaration in JavaScript. However, the most important difference between the two JS keywords is that while the var keyword is function scoped, the let keyword is block scoped.

Q: What do you understand by Closures in JavaScript?
A: Closures provide a better, concise, creative, and expressive way of writing code for JavaScript developers and programmers. Technically speaking, closures are a combination of lexical environment and function.

In other words, a closure is a locally declared variable that is related to a function and stays in the memory when the related function has returned. All local variables that were in-scope at the time of the closure creation are contained by the closure.

Following code snippet demonstrates using a normal function in JavaScript:

function greet(message) {
function greeter(name, age) {
return name + " says Hey!! He is " + age + " years old";
var message = greeter("Akhil", 26);

The aforementioned function can be represented in a better way by using closures. This is demonstrated in the following code snippet:

function greeter(name, age) {
var message = name + " says Hey!! He is " + age + " years old";
return function greet() {

// Generate the closure

var AkhilGreeter = greeter(“Akhil”, 26);

// Use the closure


Q: Please explain NEGATIVE_INFINITY in JavaScript.
A: The NEGATIVE_INFINITY is a static property in JS that results when a negative number is divided by 0. Its important characteristics are:

  • There is no need for creating a number of objects for accessing NEGATIVE_INFINITY
  • The value of the NEGATIVE_INFINITY property is the same as the negative value of the infinity property of the global object

Q: Is there any short and concise way of writing function expressions in JS?
A: JavaScript offers a short and concise way of writing function expressions known as arrow functions. This way of writing function expressions is preferred typically for non-method functions. The general syntax of an arrow function is:

const function_name = ()=>{}

Arrow functions can’t be used as constructors. Moreover, they don’t provide support for arguments, new.target, super, and this.

Q: How can you import all exports of a file as an object in JavaScript?
A: In order to import all exported members of an object, one can use:

import * as object name from ‘./file.js’

The exported methods or variables can be easily accessed by using the dot (.) operator.

Q: How will you empty an array in JavaScript?
A: There are multiple ways of emptying an array in JavaScript. Four of the most important ones are:

  • By assigning an empty array:
    var array1 = [1, 22, 24, 46];
    array1 = [];
  • By assigning array length to 0:
    var array1 = [1, 22, 24, 46];
  • By popping the elements of the array:
    var array1 = [1, 22, 24, 46];
    while(array1.length > 0) {
  • By using the splice array function:
    var array1 = [1, 22, 24, 46];
    array1.splice(0, array1.length)

Q: What do you mean by Event Bubbling and Event Capturing?
A: There are two ways for accomplishing event propagation and the order in which an event is received in the HTML DOM API.

These are Event Bubbling and Event Capturing. In the former, the event is directed towards its intended target, whereas the event goes down to the element in the latter.

  • Event Capturing – Also known as trickling, Event Capturing is rarely used. The process starts with the outermost element capturing the event and then propagating the same to the innermost element.
  • Event Bubbling – In this process, the event gets handled by the innermost element first and then propagated to the outermost element.

Q: In how many ways can you create an array in JS?
A: There are three different ways of creating an array in JavaScript, namely:

  1. By creating instance of an array:
    var someArray = new Array();
  2. By using an array constructor:
    var someArray = new Array(‘value1’, ‘value2’,…, ‘valueN’);
  3. By using an array literal:
    var someArray = [value1, value2,…., valueN];

Q: Write a code to demonstrate how to get inner HTML of an element in JavaScript.

<script type="text/javascript">
var inner= document.getElementById("inner").innerHTML ;
console.log(inner); // This is inner Element
document.getElementById("inner").innerHTML = "Html changed!";
var inner= document.getElementById("inner").innerHTML ;
console.log(inner); // Html changed!

Q: How will you remove duplicates from a JS array?
A: There are several possible ways of eliminating duplicates from a JS array. Three most-used ones are described as follows:

  1. By using Filter – It is possible to remove duplicates from an array in JavaScript by applying a filter to the same. In order to call the filter() method, three arguments are required. These are namely array, current element, and index of the current element.function unque_array (arr){
    let unique_array = arr.filter(function(elem, index, self) {
    return index == self.indexOf(elem); }
    return unique_array }
  2. By using the For loop – In this method of removing duplicate elements from an array, an empty array is used for storing all the repeating
    elements.Array dups_names = ['Akhil', 'Vijay', 'Swapnil', 'Akhil', 'Vijay'];
    function dups_array(dups_names) {
    let unique = {};
    names.forEach(function(i) {
    If (!unique[i]) {
    unique[i] = true; }
    return Object.keys(unique);}
  3. By using Set – This is the simplest approach of removing duplicate elements from an array in JS. A set is an inbuilt object for storing unique values in an array. Here’s how to use it for eliminating repeating elements from an array:function uniquearray(array) {
    let unique_array= Array.from(set(array))
    return unique_array;}In the above example, a set is created out of the array having duplicate elements. As a set is an ordered collection of unique elements, the result is an array with non-repeating elements.

Q: Can you draw a simple JavaScript DOM (Document Object Model)?
A:JavaScript DOM

Q: Write the code to force a page to load another page in JavaScript.

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

<!– location.href=”http://newhost/newpath/newfile.html”; //–></script>

Q: Please explain the Strict mode in JavaScript. Also, tell how to enable it.
A: When in the Strict Mode, JS displays errors for some code segments that might be otherwise not available. In other words, the Strict mode adds certain compulsions to the JS. It is used for removing some code mistakes that result in dropped efficiency of JS engines.

In order to enable the Strict Mode, one needs to add the string literal “use strict” above the file that needs to be opened in the Strict Mode. For example:

function somefunction() {
"use strict";
var v = "Welcome to the Strict Mode";

Q: What is the for-in loop in JavaScript? Give its syntax.

A: The for-in loop is meant to be used for looping through the properties of a JavaScript object. Every iteration of the loop results in a property of the object getting associated with the variable name. The loop continues until all the object properties are exhausted.

The general syntax of using the for-in loop is:

for (variable name in object){
statement or block to execute

Q: Tell us about the difference between .call() and .apply() functions. Give an example demonstrating the difference between the two JS functions.
A: Both .call() and .apply() functions are almost identical in their use with a major exception in the way in which arguments are passed to the function.

Because arguments are to be passed in the .call() method, it is compulsory to know about the arguments of the function. On the other hand, .apply() method is used when the number of arguments is not known. Following example demonstrates using the two functions:

var someObject = {
myProperty : 'Foo',
myMethod : function(prefix, postfix) {
alert(prefix + this.myProperty + postfix);
someObject.myMethod('<', '>');
var someOtherObject = {
myProperty : 'Bar'
someObject.myMethod.call(someOtherObject, '<', '>');
someObject.myMethod.apply(someOtherObject, ['<', '>']);

Q: What role do deferred scripts play in JavaScript?
A: During page loading, the parsing of the HTML code is paused by default until the script hasn’t stopped executing. This results in a delay in the display of the webpage if the server is slow or the script that is to be loaded is bulky.

Using deferred scripts results into a delay in the execution of the script for the time the HTML parser is running. Hence, this results in a reduction in the loading time of the webpage.

Q: Could you tell us about the various types of error constructors supported by JavaScript?
A: The Error constructor is responsible for creating an error object. Instances of the error objects are thrown when runtime errors occur. Moreover, the Error object can also be used as a base object for user-defined exceptions.

Other than the generic Error constructor, JS provides support for 7 error constructors that are:

  • EvalError – Creates an error instance regarding the global function eval().
  • InternalError – Creates an error instance regarding an internal error in the JS engine.
  • RangeError – Creates an error instance regarding a numeric variable or parameter that is outside of its valid range.
  • ReferenceError – Creates an error instance regarding de-referencing an invalid reference.
  • SyntaxError – Creates an error instance regarding a syntax error occurring while parsing code in eval().
  • TypeError – Creates an error instance regarding a parameter or variable not of a valid type.
  • URIError – Creates an error instance regarding when invalid parameters are passed to the decodeURI() or encodeURI().

Q: What do you understand by Screen objects? State their various properties.
A: In order to read the information from the client’s screen, screen objects are used in JavaScript. Properties of screen objects are:

  • AvailHeight – Gives out the height of the client screen (Excludes taskbar)
  • AvailWidth – Gives out the width of the client screen (Excludes taskbar)
  • ColorDepth – Gives out the bit depth of images supported by the client screen
  • Height – Gives out the total height of the client screen
  • Width – Gives out the total width of the client screen

Q: Could you explain escape() and unescape() functions?

A: The escape() function allows for converting a string into a coded form in JavaScript. It is used for securely transferring information from one system to another over some network. For instance, consider the following code snippet:

document.write(escape("This string is encoded!"));

The output of the aforementioned code snipped will be something like this:


The unescape() function does the exact opposite of the escape() function i.e. it decodes a coded string into the original string. Therefore, the following code snippet:


Will yield the following output:

This string is encoded!

Q: Please write JavaScript code for adding new elements dynamically.

<script type="text/javascript">
function addNode() { var newP = document.createElement("p");
var textNode = document.createTextNode(" This is a new text node");
newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); }
</script> </head>
<body> <p id="firstP">firstP<p> </body>

All done! That was the list of 20 most important JavaScript interview questions. Hope these questions will help you get a step closer to your dream JavaScript job. All the best!

Check out these best JavaScript tutorials to enhance your JS skill and knowledge.

Related Posts

Your email address will not be published. Required fields are marked *