JavaScript Interview Questions


JavaScript is one of the most widely used programming languages in the worldIt is used in almost every technical sector like web development, app development, machine learning, blockchain, etc.

It has become a crucial skill for any aspiring developer to master.

If you are looking for a job in these fields then you must have a good knowledge of JavaScript.

To help you, we have a collection of 100s of JavaScript Interview Questions that will help you to prepare boost your knowledge and will prepare you for your next interview.

Let's get started.


Interview Questions in JavaScript


1. What is JavaScript?

JavaScript is a scripting language that allows you to implement complex features on web pages. JavaScript can do things like:

  • Validate form input
  • Check if a user is logged in
  • Display a popup window
  • Change the content of an HTML element
  • Send data to a server
  • Receive data from a server
  • Update a database
  • Perform calculations
  • Graphically draw on a canvas
  • And much more!

JavaScript is everywhere! From the browser to the server, From mobile to desktop, From IoT to machine learning, It is everywhere!


2. How JavaScript is different from Java?

JavaScript and Java are completly 2 different programming language with different syntax and different purpose.

In early days, JavaScript was named as LiveScript and later it was renamed to JavaScript because of the popularity of Java.

Because of similarity in name, people often confuse JavaScript with Java. But they are completly different.

The following table shows the differences between JavaScript and Java:

JavaScript Java
JavaScript is a scripting language. Java is a programming language.
JavaScript works both on client and server side. Java works only on server side.
Prototype-based language Class-based language
Dynamic language Static language
Loosely typed language Strongly typed language
Single-threaded language Multi-threaded language
Garbage-collected language Memory-managed language
Interpreted language Compiled language

3. What is difference between == and === in JavaScript?

There are two types of equality operators in JavaScript:

  • == (equality operator)
  • === (strict equality operator)

The == operator compares two values for equality. If the values being compared are not of the same type, JavaScript will convert one type to another before making the comparison.

Whereas the === operator compares two values for equality. If the values being compared are not of the same type, then the values are considered unequal.

For any strict equality comparison, always use the === operator.

console.log(1 == '1'); // true
console.log(1 === '1'); // false

4. What is the difference between let and var in JavaScript?

let and var are two keywords used to declare variables in JavaScript.

However, there are some differences between them:

  • Scope: The main difference between let and var is in the scope. The scope of a variable declared with let is limited to the block in which it is declared, whereas the scope of a variable declared with var is the entire enclosing function.
  • Re-declaration: Variables declared with let cannot be re-declared in the same scope. But variables declared with var can be re-declared in the same scope.
  • Hoisting: let are not hoisted meaning they can't be used before they are declared. But var are hoisted so they can be used before they are declared.

5. What is the difference between null and undefined in JavaScript?

null and undefined are two special values in JavaScript. They seem similar but they are different.

null undefined
null is a special value assigned to a variable to indicate that the variable has no value. undefined is a value that is automatically assigned to a variable when it is declared but not initialized.
typeof null returns object. typeof undefined returns undefined.

6. Differentiate between Scripting and Programming Language?

A Scriptting language is generally interpreted rater than compiled. These programs are not converted into machine language.

These are generally used for automation purposes, repetative tasks or adding some functionality to a software.

Example of scripting languages are: JavaScript, VBScript, Perl, Python, PHP, etc.


On the other hand a Programming language is a language that is used to write complex programs and applications.

These programs are compiled into machine language and then executed. For example C, C++, Java, etc.


7. What does it mean by saying JavaScript is single threaded?

JavaScript can handle or process only one task at a time that's why it is called single threaded.

To handle multiple tasks JavaScript uses asynchronous programming. But this doesn't mean multiple tasks are executed at any moment. Actually tasks are queued in a certain way that it seems to handle multiple tasks.

JavaScript has only one call stack. The call stack is a data structure that records where we are in the program.


8. What is ECMAScript?

ECMAScript is a scripting language specification standardized by Ecma International. It was created to standardize JavaScript to help foster multiple independent implementations.

ECMAScript is the official name of the language. JavaScript is the common name of the language.

It has different versions like es5, es6, etc.


9. What is type coercion in JavaScript?

Type coercion is a process by which a value is converted from one type to another.

There are 2 types of type coercion in JavaScript:

  1. Implicit coercion: It is an automatic conversion of data type in certain situations. For example, comparing 2 values of different types using == operator.

    // Implicit coercion
    console.log(1 == '1'); // true
  2. Explicit coercion: This is type of conversion where we explicitly use some function to convert type. Example Number(), String(), Boolean(), etc.

    // Explicit coercion
    console.log(Number('1')); // 1

10. What is purpose of arrow function in JavaScript?

Arrow function is a new way to write a function in JavaScript. It was introduced in ES6.

Arrow functions has few advantages over normal functions:

  • Syntax of arrow function is shorter
  • this in arrow function is same as this in parent scope.
  • If there is only one statement in arrow function then it is automatically returned.

11. Why do we need to use strict mode in JavaScript?

Strict more is a feature in JavaScript that allows us to write secure and error free code.

It can be implemented by adding "use strict" at the top of the file or function.

This forces javascript to throw errors for some common mistakes like:

  • Using undeclared variables
  • Assigning value to a read-only property
  • Deleting undeletable properties
  • Using with statement
  • Using eval function

12. What is the difference between a forEach loop and a for-of loop in JavaScript?

Both forEach and for-of loops are used for iteration purposes.

  • forEach: It is an array method that iterates over and array and execute a callback function for each element of the array. It doesn't return anything.

    const arr = [1, 2, 3, 4, 5];
    arr.forEach((element) => {
      console.log(element);
    });
  • for-of: It can iterate not only over arrays but also over strings, object, sets, etc. Values of each element is assigned to a variable and then that variable is used in the loop.

    const str = 'Hello World';
    for (const element of str) {
      console.log(element);
    }

13. What is Hoisting in JavaScript?

Hoisting is mechanism in JavaScript that moves some variable and function declarations to the top of the scope they are declared in.

It is done by the JavaScript engine before the code is executed.

It is done for 2 types of declarations:

Due to this phenomenon, you can use a variable or function before it is declared (but later in the code it will be declared).

Note: Not all declarations are hoisted. Only var and normal function declarations are hoisted.

// Hoisting
a = 10;
console.log(a); // 10
var a;

hello("Jack");
function hello(name) {
  console.log("Hello " + name);
}

14. Is JavaScript case-sensitive?

Yes, JavaScript is case-sensitive. All keywords, variables, functions, and object properties are case-sensitive.

For example, a variable name is not same as Name or NAME.


15. How does JavaScript interact with HTML?

JavaScript interact with HTML using DOM (Document Object Model).

When a webpage is loaded in the browser, the browser creates a DOM of the page. It is a tree like structure that contains all the elements of the page and their properties.

Each element becomes a node in the DOM tree which can be accessed by their id, class, tag, etc.

Some of the methods of DOM are:

  • getElementById - Used to select an unique element from the webpage.
  • getElementsByClassName - Used to select all elements with a particular class.
  • getElementsByTagName - Used to select all elements with a particular tag.
  • querySelector - This methods selects first the elements that matches a given CSS selector.
  • querySelectorAll - It selects all the elements that matches a given CSS selector.

16. What is Browser Object Model (BOM)?

BOM (Browser Object Model) is an interface that provides a way to interact with the browser.

It provides various objects like window, navigator, screen, location, history, etc.

These objects provides various methods and properties that gives information and control of the browser and its environment.

console.log(window.innerHeight); // Height of the browser window
console.log(window.innerWidth); // Width of the browser window
console.log(window.location.href); // URL of the current page
console.log(window.navigator.appName); // Name of the browser
console.log(window.navigator.appVersion); // Version of the browser
console.log(window.navigator.userAgent); // User agent of the browser

17. What is immediate invoked function expression (IIFE)?

IIFE (immediate invoked function expression) is a function that gets executed immediately after it is created.

These function do not have any name because they are not going to be reused. As soon as the function is created, it is executed.

The main purpose of IIFE is to create a new scope for the variables that are declared inside it so that they do not conflict with the variables of the outer scope.

To declare an IIFE, we use the following syntax:

(function() {
  // Code
})();

// or ----------------

(function() {
  // Code
})();

You can also pass arguments to the IIFE.

(function(a, b) {
  // Code
})(10, 20);

18. What is the difference between window.onload and document.onload?

window.onload and document.onload both are used to execute a function when the page is loaded. At first glance, both seems to be same but they are not.

  1. window.onload is executed when a complete pages is loaded including all the resources like images, styles, etc.
  2. document.onload is executed when the DOM is loaded. It is executed before the images and styles are loaded.

It is recommended to use window.onload because it is executed after the page is completely loaded.


19. Define 'this' keyword in JavaScript

this in JavaScript is a very special keyword that used to refer to current object in the context of which it is used.

Suppose we have an object book with properties title and price. Now we want access the one of the property of the object inside the object itself. In this case, we can use this keyword.

Look at the code below:

const book = {
  title: 'JavaScript',
  price: 100,
  print: function() {
    console.log(this.title);
}

20. What is Closure in JavaScript?

Whenever a function is created inside another function, and internal function has access to the variables of the outer function, then the internal function becomes a closure.

Closure has access to the outer function's variables (or parent scope) even after the outer function has returned.

Here is how we can create a closure in JavaScript:

Example

function outer() {
  let a = 10;
  function inner() {
    console.log(a);
  }
  return inner;
}

const innerFunc = outer();
innerFunc(); // 10

In the above code, the inner function is a closure because it has access to the variable a of the outer function outer.

Closure is used to create private variables in JavaScript. Private variables are variables that can only be accessed inside the function in which they are declared.


21. What is the difference between call(), apply() and bind()?

call(), apply() and bind() are special methods that are used to change the value of keyword inside a function.

  • call() - It calls a function by passing the value of this keyword as the first argument.

    Other arguments of the calling function are passed from the second argument.

    Example

    function greet(name) {
      return `Hello, ${this.name}`;
    }
    
    const person = { name: 'Alex' };
    console.log(greet.call(person));

    Here we have reused the print() method of the book object to print the title of the book2 object.

  • apply() - It same as call() method but it takes the arguments as an array.

    Example

    function greet(age, salary) {
      return `Hello, ${this.name}, age: ${age}, salary: ${salary}`;
    }
    
    const person = { name: 'Alex' }
    
    console.log(greet.apply(person, [20, 35000]));
  • bind() - It calls a function and returns a new function after setting the value of this keyword.

    You can use the returned function later.

    Example

    function greet(greeting) {
      return `${greeting}, ${this.name}`;
    }
    
    const person = { name: 'Alex' };
    const greetPerson = greet.bind(person);
    console.log(greetPerson('Hello')); // 'Hello, Alex'

22. Explain recursion in JavaScript.

Recursion is a process in which a function calls itself directly or indirectly to solve a problem.

Any problem that can be broken down into smaller sub-problems can be solved using recursion.

Here is how we can create a recursive function in JavaScript:

Example

function factorial(n) {
  if (n === 1) {
    return 1;
  }
  return n * factorial(n - 1);
}

console.log(factorial(5)); // 120