blogsaboutContactPrivacy PolicyTerms & Conditions
JavaScriptjavascript_interview_questions

JavaScript Interview Questions and Answers - [2025]

March 18, 2025

23 min read

556 views

Introduction

JavaScript is one of the most popular programming languages, widely used for web development, backend services, and even mobile applications development. Even if you're a fresher or an experienced developer, mastering JavaScript interview questions is important to get your dream job. Recruiters often test candidates on JavaScript fundamentals, advanced concepts, and coding challenges to check their problem solving skills and logic building.

In this blog, we have covered top most commonly asked JavaScript interview questions and answers to help you to prepare for your interview. These questions cover basic, intermediate, and advanced topics, including ES6 features, closures, async/await, event loops, and prototypes. Also we have included JavaScript coding interview questions to ensure you're ready for both technical and conceptual interview.

Whether you're applying for a junior developer role or a senior JavaScript position, this guide will help you with the knowledge needed to pass your interview. Let's start with the JavaScript basic Interview questions:

JavaScript basic Interview Questions

In this section, we'll cover JavaScript basic interview questions that are most asked in interviews. These questions test your understanding of core JavaScript concepts such as variables, data types, scope, and operators.

1. What are the different data types in JavaScript?

JavaScript has eight primitive data types and one non-primitive data type (Object):

  • String: Represents text. Example: "Hello World", 'DevWhirl'.
  • Number: Represents numeric values (both integers and floating-point). Example: 42, 3.14.
  • BigInt: For very large integers beyond the Number range. Example: 1234567890123456789012345678901234567890n.
  • Boolean: Represents a truthy value, either true or false. Example: true, false.
  • Undefined: Represents an uninitialized variable. Example: If you declare a variable without assigning it a value, it defaults to undefined.
  • Null: Represents an empty or non existent value. Example: let value = null;.
  • Symbol: In JavaScript, a Symbol is a primitive data type that is used to create unique identifiers.
  • Object: A non-primitive data type used to store collections of data in key-value pairs.

Examples:

Here are the examples of different data types:

.js
1let name = "Depp";  // String
2let age = 34;       // Number
3let isAdult = true; // Boolean
4let height = null;  // Null
5let job;            // Undefined
6let symbol = Symbol('description'); // Symbol
7
8let person = { name: 'John', age: 30 }; // object

2. What is the difference between var, let, and const?

This is the most asked in JavaScript interview questions. var, let, and const are all used to declare variables, but they have different behaviors, scope rules, and usage. Here's the differences between them:

  • var: It is function-scoped and allows re-declaration. Variables declared using var are hoisted to the top of their scope but initialized with undefined.
  • let: It is block-scoped and cannot be re-declared within the same scope. Variables declared with let are also hoisted, but not initialized.
  • const: It is also block-scoped but cannot be re-assigned. Once a variable is assigned a value with const, it is constant. Like let, variables declared with const are hoisted but not initialized.

Example:

Here are the example of the variables in JavaScript:

.js
1var x = 10;  // Can be re-declared and updated
2let y = 20;  // Cannot be re-declared but can be updated
3const z = 30;  // Cannot be re-declared or updated
4
5x = 15;  
6y = 25;  
7z = 35;  // Error: Assignment to constant variable

Here is the another example for better understanding of function-scoped variables and block-scope variables:

.js
1// var (function-scoped)
2if (true) {
3var x = 10;
4}
5console.log(x); // 10 (works outside the block)
6
7// let (block-scoped)
8if (true) {
9let y = 20;
10}
11console.log(y); // Error: y is not defined
12
13// const (immutable binding)
14const PI = 3.14;
15PI = 3.1416; // Error: Assignment to constant variable
16
17// But objects/arrays can be modified:
18const user = { name: "Depp" };
19user.name = "Bob"; // Allowed

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

== and === both are comparison operators in JavaScript. Here is the difference between them:

  • == (Loose Equality): It compares only the values and performs type coercion. JavaScript will try to convert the values to the same type before comparing them.
  • === (Strict Equality): It compares both the value and type without any type coercion. It only returns true if both are of the same type and have the same value.

Example:

.js
15 == "5";   // true (string "5" is converted to number 5)
25 === "5";  // false (number vs string)
3true == 1;  // true (1 is truthy)
4true === 1; // false (boolean vs number)

4. What is the difference between null and undefined?

In JavaScript, null and undefined are both primitive values, but they serve different concepts:

  • null: Represents an intentional absence of value. It is assigned explicitly to indicate that a variable is empty.
  • undefined: Means a variable has been declared but has not been assigned any value.

Example:

.js
1let a; // Undefined, since no value is assigned
2let b = null; // Null, explicitly assigned as empty
3console.log(a);  // Output: undefined
4console.log(b);  // Output: null

5. What is the difference between forEach(), map(), and filter()?

In JavaScript, forEach(), map(), and filter() are array methods that allow you to iterate over arrays and perform operations. However, they have different behaviors and use cases. Here's a breakdown of the differences:

  • forEach(): Executes a provided function once for each element in an array. It doesn't return anything (returns undefined) and cannot modify the original array.
  • map(): Transforms every element in the array based on the function provided and returns a new array. It doesn't modify the original array.
  • filter(): Filters elements from the array based on a provided condition and returns a new array with the filtered elements. It doesn't modify the original array.

Example:

.js
1const numbers = [1, 2, 3];
2
3// forEach (no return)
4numbers.forEach(num => console.log(num * 2)); // Logs: 2, 4, 6
5
6// map (returns new array)
7const doubled = numbers.map(num => num * 2); // [2, 4, 6]
8
9// filter (returns filtered array)
10const even = numbers.filter(num => num % 2 === 0); // [2]

6. What is an Immediately Invoked Function Expression (IIFE)?

An Immediately Invoked Function Expression (IIFE) is a JavaScript function that runs as soon as it is defined. The main idea is that the function is created and then immediately executed, without having to call it later.

Example:

.js
1(function() {
2 // Code here runs immediately
3console.log("IIFE executed!");
4})(); // Output: IIFE executed!

7. What are template literals in JavaScript?

Template literals are strings that allow for multi-line strings and string interpolation using backticks (`) instead of regular quotes.

  • They support expressions inside $.
  • They can span multiple lines without the need for escape characters.

Example:

.js
1let name = "Depp";
2let age = 34;
3console.log(`Hello, my name is ${name} and I am ${age} years old.`);  
4// Output: Hello, my name is Depp and I am 34 years old.

8. What is a Closure?

A closure in JavaScript is a function that has access to its own scope, the lexical scope (the scope in which it was defined), and the global scope, even after the outer function has finished executing.

Example:

.js
1function outer() {
2let outerVariable = 'I am from the outer function!';
3
4  function inner() {
5      console.log(outerVariable);  // inner function can access outerVariable
6  }
7
8return inner;  // Return the inner function (which forms the closure)
9}
10
11const closureFunction = outer();  // outer() is called, but it returns the inner function
12closureFunction();  // Logs: 'I am from the outer function!'

Explanation:

  • When outer() is called, it defines a variable outerVariable and the inner() function.
  • The inner() function is returned from the outer() function, creating a closure.
  • Even though outer() finishes executing, closureFunction() (which is the inner() function) still has access to outerVariable because the closure "remembers" the environment in which it was created.

9. Explain the this keyword in JavaScript

The this keyword in JavaScript refers to the context in which a function is called. It points to the object that is calling the function.

  • In global context, this refers to the global object (e.g., window in the browser).
  • Inside a method, this refers to the object that owns the method.
  • In arrow functions, this is lexically bound, meaning it inherits the this value from the surrounding code.

Example:

.js
1// In a method
2const person = {
3name: "John",
4greet: function() {
5  console.log(this.name);  // Output: John
6}
7};
8
9person.greet();
10
11// In an arrow function (this is lexically bound)
12const greet = () => console.log(this); 
13// 'this' refers to the surrounding context (window object in browser)
14greet();

The this keyword in JavaScript is behaves differently depending on where and how it is used. It is important to understand how this works to avoid common issues, especially in functions, methods, and object-oriented programming.

10. Mention some advantages of JavaScript.

Here are the some advantages of using JavaScript:

  • Versatile: JavaScript can be used for both client-side and server-side programming (with Node.js).
  • Easy to Learn: It has a simplified syntax compared to other programming languages like Java or C++.
  • Wide Support: JavaScript is supported by all modern web browsers, making it essential for web development.
  • Asynchronous Programming: JavaScript can handle asynchronous operations like AJAX requests and event handling through callbacks, promises, and async/await.
  • Supports both OOP and functional programming.

11. What is BOM and DOM?

  • BOM (Browser Object Model): Represents the browser s window and its components (such as window, navigator, screen, etc.). It provides methods to interact with the browser environment, like changing the window size, controlling the history, etc.
  • DOM (Document Object Model): Represents the web page and its elements in a tree-like structure. It allows developers to manipulate the page content, structure, and styles dynamically using JavaScript.

Example:

.js
1// BOM Example
2console.log(window.innerHeight);  // Get browser window height
3
4// DOM Example
5document.getElementById("header").style.color = "blue";  // Change the color of an element

12. What is Hoisting in JavaScript?

Hoisting in JavaScript is a behavior where variable and function declarations are moved to the top of their containing scope during the execution phase, before the code is actually executed. This applies to variables (var, let, const) and function declarations.

  • For var declarations, the declaration is hoisted but not the initialization.
  • For let and const, the declarations are hoisted but cannot be accessed before initialization (they enter a temporal dead zone).
  • Function declarations are hoisted along with their definitions.

Example:

.js
1console.log(a);  // Output: undefined (due to hoisting with `var`)
2
3// Hoisting behavior with `let` and `const`:
4console.log(b);  // Error: Cannot access 'b' before initialization
5let b = 10;
6
7myFunction();  // Output: "Function is hoisted"
8function myFunction() {
9console.log("Function is hoisted");
10}

13. What is a Callback in JavaScript?

A callback is a function that is passed as an argument to another function and is executed after the completion of some operation or event. It's a way of ensuring that a certain piece of code runs only after another piece of code has finished executing.

Callbacks are commonly used in JavaScript for asynchronous operations, like reading files, making HTTP requests, or handling user events, to avoid blocking the main execution flow.

Example:

.js
1// Simple callback example
2
3function greet(name, callback) {
4console.log("Hello, " + name);
5callback();  // Calling the callback function after the greeting
6}
7
8function thankYou() {
9console.log("Thank you for using our service!");
10}
11
12// Passing the 'thankYou' function as a callback
13greet("Depp", thankYou);
14
15// Output:
16// Hello, Depp
17// Thank you for using our service!

In this example:

  • greet is the parent function, and thankYou is the callback function passed to greet.
  • The callback thankYou is executed after greet prints the greeting.

Advanced JavaScript Interview Questions

In this section, we will cover advanced JavaScript interview questions that focus on advance concepts such as closures, prototypes, asynchronous programming, and more. These concepts are important for an experienced JavaScript developers.

1. What is the Difference Between Synchronous and Asynchronous JavaScript?

In JavaScript, synchronous and asynchronous execution refers to how code is executed in relation to time and blocking behavior.

Synchronous JavaScript

Synchronous code is executed line by line, in the order it appears in the script. Each operation must complete before the next one starts.

  • Executes one task at a time.

  • Each operation blocks the execution of the next operation until it completes.

    Example of Synchronous Code:

    .js
    1console.log("Start");
    2
    3 for (let i = 0; i < 3; i++) {
    4    console.log(i);
    5}
    6
    7console.log("End");
    8
    9// output will be 
    10Start
    110
    121
    132
    14End
    • Each line is executed in order.
    • If a line takes time, the whole program waits for it.

Asynchronous JavaScript

Asynchronous code allows non-blocking execution. Some operations (like network requests or timers) can run in the background while JavaScript continues executing other code.

  • Executes non-blocking operations.

  • Uses callbacks, Promises, or async/await to handle delayed execution.

    Example of Asynchronous Code:

    .js
    1console.log("Start");
    2
    3setTimeout(() => {
    4    console.log("Inside setTimeout");
    5}, 2000); // Runs after 2 seconds
    6
    7  console.log("End");
    8
    9// output will be 
    10Start
    11End
    12Inside setTimeout
    • setTimeout() is asynchronous, so the program doesn't wait for it.
    • "End" is logged before "Inside setTimeout" because JavaScript moves on to the next task while waiting.

2. What are JavaScript Promises?

A Promise in JavaScript represents the result of an asynchronous operation that may either resolve successfully or fail.

States of a Promise:

  • Pending: Initial state, neither fulfilled nor rejected (a loading state).
  • Resolved (Fulfilled): The operation was successful.
  • Rejected : The operation failed.

Example:

.js
1let myPromise = new Promise((resolve, reject) => {
2let success = true;
3setTimeout(() => {
4  if (success) {
5    resolve("Operation Successful");
6  } else {
7    reject("Operation Failed");
8  }
9}, 2000);
10});
11
12myPromise
13.then(result => console.log(result))  // Handles success
14.catch(error => console.log(error));  // Handles failure
15
16// output after 2 seconds
17
18Operation Successful

If success was false, it would print "Operation Failed".

3. What is Async/Await?

async/await is a modern way to handle asynchronous operations in JavaScript. It makes asynchronous code look and behave more like synchronous code, improving readability and maintainability.

Before async/await, JavaScript used callbacks and Promises to handle asynchronous tasks.

Example:

.js
1async function fetchData() {
2const data = await fetch("https://jsonplaceholder.typicode.com/posts");
3const json = await data.json(); // Await waits for the data to be converted to JSON
4console.log(json);
5}
6
7fetchData();
  • await pauses the execution of the function until the promise returned by fetch() resolves.
  • Once resolved, it proceeds with the next line and logs the result.

4. What is a Closure in JavaScript?

A closure is when a function remembers and continues to access variables from its parent scope even after the parent function has finished execution.

Example:

.js
1function outerFunction() {
2let count = 0;
3
4return function innerFunction() {
5  count++;
6  console.log(count);
7};
8}
9
10const counter = outerFunction();
11counter(); // 1
12counter(); // 2
13counter(); // 3

Even though outerFunction() has finished executing, innerFunction() still has access to count.

5. What is the Prototype Chain in JavaScript?

The Prototype Chain in JavaScript is a mechanism that allows objects to inherit properties and methods from other objects.

What is a Prototype?

In JavaScript, every object has a prototype, which is another object that it inherits properties and methods from.

Example: Checking an Object Prototype

.js
1const obj = {};
2console.log(Object.getPrototypeOf(obj)); // Output: {} (Prototype object)

Every object in JavaScript is linked to a prototype.

How the Prototype Chain Works

When you try to access a property or method on an object:

  • JavaScript first looks for it in the object itself.
  • If it's not found, JavaScript looks at the object's prototype.
  • If still not found, it keeps checking higher in the prototype chain.
  • If JavaScript reaches the top-level prototype (null) and still doesn't find the property, it returns undefined.

Example: Prototype Chain in Action

.js
1const animal = {
2eat() {
3  console.log("This animal eats food.");
4}
5};
6
7const dog = Object.create(animal); // dog inherits from animal
8dog.bark = function() {
9console.log("Woof! Woof!");
10};
11
12dog.eat(); // Output: "This animal eats food."
13dog.bark(); // Output: "Woof! Woof!"

Here:

  • dog doesn't have an eat() method.
  • JavaScript looks in dog's prototype (animal), finds eat(), and executes it.

6. What is the Event Loop in JavaScript?

The Event Loop in JavaScript is the mechanism that handles asynchronous operations and ensures that JavaScript executes code in the correct order.

Event Loop Process:

  • Executes synchronous code (Call Stack).
  • Moves async tasks (like setTimeout, Promises) to Web APIs.
  • Once the Call Stack is empty, moves pending tasks to the Stack.

Example:

.js
1console.log("Start");
2
3setTimeout(() => console.log("Inside setTimeout"), 0);
4
5Promise.resolve().then(() => console.log("Inside Promise"));
6
7console.log("End");
8
9// Output will be:
10
11Start
12End
13Inside Promise
14Inside setTimeout

Even though setTimeout() is set to 0ms, it runs after the Promise due to event loop behavior.

7. What is Debouncing and Throttling in JavaScript?

Debouncing and Throttling are two performance optimization techniques in javascript that control how frequently a function executes in response to events like scrolling, resizing, and typing.

What is Debouncing?

Debouncing ensures that a function only executes after a delay and resets the timer if the event happens again before the delay is over.

Example: Debouncing in JavaScript

.js
1function debounce(func, delay) {
2let timer;
3return function (...args) {
4  clearTimeout(timer); // Reset the timer if the event happens again
5  timer = setTimeout(() => func.apply(this, args), delay);
6};
7}
8
9// Function to execute
10function searchQuery() {
11console.log("API Call: Searching...");
12}
13
14const debouncedSearch = debounce(searchQuery, 500);
15
16// Simulating typing
17debouncedSearch(); // If the user types again within 500ms, it resets the timer
18debouncedSearch();
19debouncedSearch(); // Executes only once after 500ms of no typing
  • Each time the user types a character, debouncedSearch() is called.
  • The timer resets if the user types again within 500ms.
  • The function only executes after the user stops typing for 500ms.

What is Throttling?

Throttling ensures that a function executes at most once in a given time interval, no matter how many times the event occurs.

Example: Throttling in JavaScript

.js
1function throttle(func, limit) {
2let inThrottle;
3return function (...args) {
4  if (!inThrottle) {
5    func.apply(this, args);
6    inThrottle = true;
7    setTimeout(() => (inThrottle = false), limit);
8  }
9};
10}
11
12// Function to execute
13function logScroll() {
14console.log("User is scrolling...");
15}
16
17const throttledScroll = throttle(logScroll, 1000);
18
19window.addEventListener("scroll", throttledScroll);
  • The function executes immediately when the event happens.
  • It ignores all calls for the next 1000ms (1 second).
  • After 1 second, it allows execution again.

Which One Should You Use?

  • Use Debouncing when you only need the final event (e.g., API search after user stops typing).
  • Use Throttling when you need regular updates but want to limit excessive calls (e.g., handling scroll or resize events efficiently).

8. What is the Difference Between Call, Apply, and Bind?

In JavaScript, call(), apply(), and bind() are methods used to change the this context of a function.

.js
1let obj = { name: "Depp" };
2
3function greet(age) {
4console.log(`Hello, my name is ${this.name} and I am ${age} years old.`);
5}
6
7// Using call
8greet.call(obj, 25);  // Hello, my name is Depp and I am 25 years old.
9
10// Using apply
11greet.apply(obj, [25]);  // Same output
12
13// Using bind
14let newGreet = greet.bind(obj, 25);
15newGreet();  // Executes later with bound context
  • call() invokes immediately with arguments passed separately.
  • apply() invokes immediately with arguments in an array.
  • bind() returns a new function with this bound.

9. What is Currying?

Currying is a technique in JavaScript (and other functional programming languages) where a function that takes multiple arguments is transformed into a sequence of functions, each taking one argument at a time.

Example of Currying

Without Currying:

.js
1function add(a, b) {
2return a + b;
3}
4
5console.log(add(2, 3)); // 5

With Currying:

.js
1function add(a) {
2return function (b) {
3  return a + b;
4};
5}
6
7const add2 = add(2); // Returns a new function
8console.log(add2(3)); // 5
  • The function add(a) returns a new function that takes b as an argument.
  • When you call add(2), it returns a new function that adds 2 to the argument b.
  • Calling add2(3) gives you 5 because 2 + 3 = 5.

JavaScript Coding Interview Questions

This section focuses on JavaScript Coding Interview Questions asked in JavaScript interviews. These questions test your problem-solving skills and understanding of core JavaScript concepts. So let's start JavaScript Coding Interview Questions

1. Write a Function to Reverse a String in JavaScript.

Reversing a string is a common coding interview problem. The challenge is to create a function that takes a string as input and returns it in reverse order.

Example:

.js
1function reverseString(str) {
2return str.split('').reverse().join('');
3}
4
5console.log(reverseString("Hello"));  // Output: "olleH"
  • split('') converts the string into an array of characters.
  • reverse() reverses the array in place.
  • join('') joins the array back into a string.

2. Check if a String is a Palindrome.

A palindrome is a word, phrase, or number that reads the same forwards and backwards. The goal is to check if the given string is a palindrome.

Example:

.js
1function isPalindrome(str) {
2const cleanedStr = str.replace(/[^A-Za-z0-9]/g, '').toLowerCase();  
3// Remove non-alphanumeric characters and convert to lowercase
4return cleanedStr === cleanedStr.split('').reverse().join('');
5}
6
7console.log(isPalindrome("A man, a plan, a canal, Panama"));  // Output: true
  • We clean the string by removing all non-alphanumeric characters and converting it to lowercase to ensure case-insensitivity.
  • Then, we check if the string is the same when reversed.

3. Find the Largest Number in an Array.

This coding problem tests your ability to loop through an array and find the largest element.

Example:

.js
1function findLargestNumber(arr) {
2return Math.max(...arr);
3}
4
5console.log(findLargestNumber([10, 5, 100, 20]));  // Output: 100
  • Math.max() finds the maximum value in the array. The spread operator (...) is used to pass the elements of the array as individual arguments to Math.max().

4. Remove Duplicate Values from an Array.

This problem asks you to remove duplicate values from an array and return a new array with unique values.

Example:

.js
1function removeDuplicates(arr) {
2return [...new Set(arr)];
3}
4
5console.log(removeDuplicates([1, 2, 3, 2, 4, 5, 3]));  // Output: [1, 2, 3, 4, 5]
  • new Set(arr) creates a Set from the array, which automatically removes duplicate values because sets cannot contain duplicates.
  • The spread operator (...) is used to convert the Set back into an array.

5. Sum of All Elements in an Array.

This is a simple problem where you sum all the elements of an array.

Example:

.js
1function sumArray(arr) {
2return arr.reduce((acc, num) => acc + num, 0);
3}
4
5console.log(sumArray([1, 2, 3, 4]));  // Output: 10
  • reduce() is used to iterate over the array and accumulate the sum of the elements.

6. Write the function to find the vowels

To find the vowels in a given string in JavaScript, you can loop through the string and check if each character is a vowel (a, e, i, o, u). Here's an example code to find vowels:

Example:

.js
1function findVowels(str) {
2const vowels = "aeiouAEIOU"; // Define all vowels (uppercase and lowercase)
3let vowelList = []; // Array to store vowels found in the string
4
5// Loop through the string and check for vowels
6for (let i = 0; i < str.length; i++) {
7  if (vowels.includes(str[i])) {
8    vowelList.push(str[i]); // Add vowel to the list
9  }
10}
11
12return vowelList;
13}
14
15// Example usage:
16const result = findVowels("Hello World!");
17console.log(result); // Output: ["e", "o", "o"]
  • vowels: A string that contains both uppercase and lowercase vowels.
  • Loop through the string: The function loops through each character in the input string (str).
  • includes() method: Checks if the character is a vowel by seeing if it's included in the vowels string.
  • Storing vowels: All vowels found are stored in the vowelList array.

These JavaScript coding interview questions test various fundamental concepts including array manipulation, recursion, string operations, and understanding of basic algorithms. Preparing for such questions will help you in both interviews and in building stronger problem-solving skills with JavaScript.

Frequently Asked Questions

  • Q: How can I improve my problem-solving skills for JavaScript Coding Interview Questions?

    A: To improve your problem-solving skills, practice solving coding challenges on platforms like LeetCode, Codewars, and HackerRank. Start with easy problems, gradually move to medium and hard ones. Focus on understanding algorithms and data structures like arrays, strings, stacks, queues, and trees. Additionally, practice writing clean, efficient code and work on optimizing your solutions to improve performance.

  • Q: Should I learn JavaScript frameworks to prepare for an interview?

    A: While knowing JavaScript frameworks is essential, especially for positions requiring frameworks like React or Node.js, make sure to have a strong understanding of core JavaScript concepts first. Many interviewers test fundamental JavaScript knowledge before moving to frameworks. After you're comfortable with vanilla JavaScript, move into popular frameworks and libraries relevant to the job you're applying for. Check ReactJs interview Questions

  • Q: How important is knowing ES6+ features for a JavaScript interview?

    A: ES6+ features are commonly used in modern JavaScript development, so it's important to understand them. Topics like arrow functions, let/const, template literals, destructuring, async/await, and spread/rest operators frequently come up in interviews. Knowing these features will make your code more modern which is often a key point in technical interviews.

Conclusion

Preparing for a JavaScript interview questions requires a solid understanding of both core concepts and advanced topics. From mastering the basics like data types, functions, and scopes, to complex topics such as closures, promises, and asynchronous programming, both helping you perform well in your interview.

By practicing JavaScript Coding Interview Questions you'll be able to tackle JavaScript interview questions confidently.

If you found this blog helpful, feel free to share it with others who may benefit from it!

Share this article

On this page: