Important 20 JavaScript Interview Questions and Answers

  • By Shital Chauhan
  • January 17, 2025
  • JavaScript
Important 20 JavaScript Interview Questions and Answers

Important 20 JavaScript Interview Questions and Answers

Prepare for your next tech role with these Important 20 JavaScript Interview Questions and Answers, covering concepts, coding examples, and best practices.

 

1. What are the different data types in JavaScript?

  Answer: JavaScript has two types of data:

  • Primitive types: string, number, boolean, null, undefined, symbol, bigint.
  • Non-primitive types: object (including arrays, functions, and objects)

 

  1. What is the difference between var, let, and const?
      Answer:
  • var: Function-scoped, can be re-declared and updated, hoisted with undefined.
  • let: Block-scoped, cannot be re-declared in the same scope but can be updated.
  • const: Block-scoped, cannot be re-declared or updated (though objects can have their properties modified).

 

3. What is a closure in JavaScript?
Answer:
A closure is a function that has access to its own scope, the scope of the outer function, and the global scope even after the outer function has returned.

function outerFunction() {

  let count = 0;

   return function innerFunction() {

     count++;

     return count;

  };

}

 

const counter = outerFunction();

console.log(counter()); // 1

console.log(counter()); // 

 

4. What is the difference between == and ===?

 Answer:

  • ==: Compares values after type coercion (e.g., 5 == ‘5’ is true).
  • ===: Strict equality, checks both value and type (e.g., 5 === ‘5’ is false).

 

5. Explain the difference between map(), filter(), and reduce().

Answer:

    • map(): Transforms each element of an array and returns a new array.
    • filter(): Filters elements based on a condition and returns a new array.
    • reduce(): Reduces an array to a single value by applying a function iteratively.
  • Ex:

const numbers = [1, 2, 3, 4];

 

const doubled = numbers.map((n) => n * 2); // [2, 4, 6, 8]

const even = numbers.filter((n) => n % 2 === 0); // [2, 4]

const sum = numbers.reduce((acc, n) => acc + n, 0); // 10.

 

 6. What is hoisting in JavaScript?

 Answer:
Hoisting is JavaScript’s default behavior of moving declarations (variables and functions) to the top of their scope before execution.

Ex:

console.log(a); // undefined

var a = 5;

// Function hoisting

hoistedFunction(); // “I am hoisted”

function hoistedFunction() {

   console.log(“I am hoisted”);

}

 

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

Answer:

  • undefined: A variable has been declared but has not been assigned a value yet.
  • null: Represents an intentional absence of any object value. It is explicitly assigned to a variable to indicate that it does not hold any value.

Ex:

let a; // undefined

let b = null; // null

 

8. What are JavaScript “Promises” and how do they work internally?

Answer:
A Promise is an object representing the eventual completion or failure of an asynchronous operation. Internally, a promise is in one of three states:

  • Pending: The operation is still in progress.
  • Resolved: The operation has been completed successfully.
  • Rejected: The operation failed.

 

Internally, Promises are implemented using a callback queue (microtask queue). They provide .then(), .catch(), and .finally() methods to handle success, failure, and cleanup.

 

Ex:

const myPromise = new Promise((resolve, reject) => {

  const success = true;

  if (success) {

    resolve(“Success!”);

  } else {

    reject(“Failure!”);

  }

});

 

myPromise.then((result) => console.log(result)).catch((error) => console.log(error));

 

 9. What are async and await in JavaScript?

Answer:
async and await simplify working with Promises and asynchronous code.

  • async: Declares a function as asynchronous, automatically returning a Promise.
  • await: Can only be used inside an async function, and pauses the execution of the function until the Promise resolves or rejects.

 

async function fetchData() {

  try {

    let response = await fetch(“https://api.example.com/data”);

    let data = await response.json();

    console.log(data);

  } catch (error) {

    console.error(“Error fetching data:”, error);

  }

}

 

fetchData();

 

 10. What does the addEventListener() method do?

 Answer:
addEventListener() is used to attach an event handler to an element. It allows you to listen for and respond to events like clicks, keypresses, etc., without overwriting existing event listeners.

Ex:

const button = document.getElementById(‘myButton’);

button.addEventListener(‘click’, function() {

  alert(‘Button clicked!’);

});

 

 11. What is the difference between event.preventDefault() and event.stopPropagation()?

Answer:

  • event.preventDefault(): Prevents the default behavior of the event (e.g., form submission or link navigation).
  • event.stopPropagation(): Stops the event from propagating (bubbling) up the DOM, preventing any parent event listeners from being triggered.

Ex:

document.getElementById(‘myForm’).addEventListener(‘submit’, function(event) {

  event.preventDefault(); // Prevent form submission

});

 

 12. What is a callback function in JavaScript?

Answer:
A callback function is a function passed as an argument to another function and is executed after a certain task is completed, usually asynchronously. It is often used in asynchronous operations like reading a file, making an API call, etc.

Ex:

function fetchData(callback) {

  setTimeout(() => {

    console.log(“Data fetched”);

    callback(); // Calling the callback after fetching data

  }, 1000);

}

 

fetchData(function() {

  console.log(“Callback executed”);

});

 

 13. What is the purpose of the setTimeout() and setInterval() methods in JavaScript?

Answer:

  • setTimeout(): Executes a function once after a specified delay.
  • setInterval(): Executes a function repeatedly at regular intervals until cleared.

Ex:

setTimeout(() => {

  console.log(“Run once after delay”);

}, 1000);

 

const interval = setInterval(() => {

  console.log(“This repeats every 2 seconds”);

}, 2000);

 

// To stop the interval

clearInterval(interval);

 

 14. What is event delegation in JavaScript?

Answer:
Event delegation is a technique where you attach a single event listener to a parent element to manage events for its child elements. It works because events bubble up from the target element to the parent, allowing you to catch them at the parent level.

Ex:

document.getElementById(‘parent’).addEventListener(‘click’, function(e) {

  if (e.target && e.target.matches(‘button.classname’)) {

    console.log(‘Button clicked’);

  }

});

 

 15. What is DOM in Javascript?

DOM is a memory representation of an HTML page where each element is considered as a node/object. DOM has some properties and some methods

Used for DOM manipulations. 

Ex: 

Functions: 

document.getElementById(“id”) , document.getElementByTagName(“Name”);

Properties:

innerHTML, nodeValue,nodeName etc..

 

 16. Can an array hold different types of elements in javascript??

Answer:

Yes, an array can hold different types of elements in it as it considered as Object in javascript. It’s dynamic in nature and not like an array in C, JAVA-like languages.

Ex:

Const arr=[“Neha”,23,”Pune”,67.8];

Console.log(arr);// [Neha,23,Pune,67.8]

 

 17. What are higher-order functions in JavaScript?

Answer:
Higher-order functions are functions that can take other functions as arguments, return functions, or both.

Ex:

function higherOrderFunction(callback) {

  return callback(5);

}

 

function square(num) {

  return num * num;

}

 

console.log(higherOrderFunction(square)); // 25

 

 18. Name any three pre-defined functions in JavaScript??

Answer:

str1=”Hello”,str2=”world”

Ex: 

console.log(str1.charAt(0));// H 

console.log(str1.concat(“ “,str2));// Hello world

console.log(str.toLowerCase()); // ‘hello world’

 

 19. How do we represent the data type of variable in javascript??

Answer:

typeof(var_name) operator is used to know the data type of variable.

Ex:

var name=”Mohit”; var id=101;

Console.log(typeof(name));// string

Console.log(typeof(id));// number

 

 20. What are Asynchronous functions in JavaScript??

Answer:

JavaScript asynchronous functions are used to execute tasks that may take time 

To complete without blocking the without blocking the execution of other code.

Mechanisms used for asynchronous JavaScript are:

Callback functions

Promises

async and await

 

Note: Do watch our latest video: Click Here

Author:-

Shital Chauhan
Call the Trainer and Book your free demo class for JavaScript now!!!

© Copyright 2020 | SevenMentor Pvt Ltd.