Home > Interview > Top 50+ JavaScript Interview Questions with Answers for 2024

Top 50+ JavaScript Interview Questions with Answers for 2024

author

Akancha Chhetri

Content Writer | Updated: November 26, 2024 21:35 NST

JavaScript is one of the most widely used programming languages for building dynamic websites and web applications. Whether you are preparing for a front-end or full-stack developer role, mastering JavaScript is essential. In this article, we have compiled a list of the most frequently asked JavaScript interview questions and answers to help you prepare for your next interview. From core concepts like variables and functions to advanced topics like closures, event handling, and asynchronous programming, this guide covers everything you need to succeed.

Javascript Interview Questions for Freshers

1. What is JavaScript?

Answer: JavaScript is a scripting language that enables interactive web experiences by manipulating DOM elements and handling user events. It works alongside HTML and CSS to transform static web pages into dynamic applications. JavaScript runs natively in all modern web browsers, making it universally accessible and essential for web development.

JavaScript was created by Brendan Eich in 1995 while he worked at Netscape. It was first named Mocha, then changed to LiveScript, and finally became known as JavaScript.

2. How does JavaScript differ from Java?

Answer: JavaScript and Java are often confused due to their similar names, but they are quite different in several key aspects. Here’s how JavaScript differs from Java:

JavaScript Java
Runs in the web browser (client-side) and server-side (Node.js). Runs on the Java Virtual Machine (JVM).
Interpreted language; executed directly by the browser or runtime environment. Compiled into bytecode and executed by the JVM.
Dynamically typed; variable types are determined at runtime. Statically typed; variable types must be declared and checked during compilation.
More flexible, no need to declare variable types (e.g., let, var, const). Requires explicit variable declarations (e.g., int, String).

3. What is ECMAScript?

Answer: ECMAScript is a standard for scripting languages, including JavaScript. It was developed by ECMA International to ensure that web pages work consistently across different browsers. This standard defines the core features and rules for how the language should behave, making it easier for developers to write code that runs smoothly everywhere.

4. What are variables in JavaScript?

Answer: Variables are containers used to store data values. It can store different types of values, such as numbers, strings, objects, and arrays. In JavaScript, variables can be declared using three main keywords:

  • var
  • let
  • const

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

Answer: The differences between var, let, and const in JavaScript are as follows:

var let const
Function-scoped: Accessible within the function where it's declared. Block-scoped: Accessible only within the block where declared. Block-scoped: Accessible only within the block where declared.
variables can be updated and reassigned. variables can be updated and reassigned. variables cannot be reassigned after the initial assignment. However, object properties can be modified.
It is used for variables that need function-wide or global access It is used for block-scoped variables that may change It is used for constants or values that should not change
It is hoisted to the top of the function or global context Hoisted but not initialized, leading to a "Temporal Dead Zone" (TDZ) until declared. Hoisted but not initialized, leading to a "Temporal Dead Zone" (TDZ) until declared.

6. What is JavaScript hoisting? How does it affect variables and functions?

Answer: JavaScript Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their respective scopes during the compilation phase. Hoisting behavior differs based on how the variable or function is defined:

  • var variables are hoisted and initialized as undefined.
  • let and const variables are hoisted but remain uninitialized until their declaration is reached, resulting in a ReferenceError if accessed until they are declared.
  • Function declarations are fully hoisted and can be called before their definition, while function expressions only hoist the variable declaration, not the assignment.

7. How do you check for the data type of a variable in JavaScript?

Answer: To check for the data type of a variable in JavaScript, you can use the typeof operator. This operator returns a string indicating the type of the operand, which can be any variable, function, or object.

Basic Syntax

typeof variableName;

8. What are the primitive data types in JavaScript?

Answer: In JavaScript, there are seven primitive data types. These types are immutable and used for simple data values.

  • String: Represents a sequence of characters used for text. Strings can be enclosed in single quotes, double quotes, or backticks (for template literals).
  • Number: Represents both integer and floating-point numbers. JavaScript does not differentiate between different types of numbers.
  • Boolean: Represents a logical entity that can be either true or false. Commonly used in conditional statements.
  • Bigint: Represents integers with arbitrary precision, allowing for the representation of large numbers beyond the safe integer limit. BigInts are created by appending n to the end of a number.
  • Symbol: A unique and immutable value often used as object property keys to avoid name clashes. Each symbol is unique, even if they have the same description.
  • Null: Represents the intentional absence of any object value. It is often used to indicate that a variable should have no value.
  • Undefined: Indicates that a variable has been declared but has not yet been assigned a value. It is the default value for uninitialized variables.

9. Explain the difference between null and undefined.

Answer: In JavaScript, null and undefined are two distinct types that represent the absence of a value, but they serve different purposes and have different behaviors. 

null: This is a primitive value that represents an intentionally defined absence of any value. It is often used to indicate that a variable should have no value or to clear a variable.

undefined: This is also a primitive value, but it signifies that a variable has been declared but has not yet been assigned a value. It is the default value for uninitialized variables.

10. What is type coercion in JavaScript?

Answer: Type coercion in JavaScript is the automatic conversion of values from one data type to another. This process happens when JavaScript expects a certain type but is provided with another, and it tries to convert the given value into the expected type.

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

Answer: The key differences between == and === are as follows:

== ===
It converts values to the same type before comparison. It compares values as-is without type conversion.
It can give unexpected results due to implicit type conversion. It is more predictable and exact since types must match.

12. How do arithmetic, comparison, and logical operators work in JavaScript?

Answer: In JavaScript, operators are essential for performing various operations on values. They can be categorized into arithmetic, comparison, and logical operators. Here’s a detailed overview of how each type works.

Operator Description Example
+ Addition 5 + 3 results in 8
- Subtraction 5 - 3 results in 2
* Multiplication 5 * 3 results in 15
/ Division 6 / 3 results in 2
% Modulus (remainder) 5 % 2 results in 1
++ Increment let x = 5; x++ results in 6
-- Decrement let x = 5; x-- results in 4

Comparison Operators

Comparison operators are used to compare two values and return a boolean result (true or false). The main comparison operators include:

Operator Description Example
== Loose equality (coerces types) 3 == '3' returns true
=== Strict equality (no type coercion) 3 === '3' returns false
!= Loose inequality 3 != '4' returns true
!== Strict inequality 3 !== '3' returns true
< Less than 2 < 3 returns true
> Greater than 3 > 2 returns true
<= Less than or equal to 2 <= 2 returns true
>= Greater than or equal to 3 >= 2 returns true

Logical Operators

Logical operators are used to combine multiple boolean expressions. The primary logical operators include:
Operator Description Example
&& Logical AND: returns true if both operands are true. (x < 6) && (y < 5) returns true if both conditions are true.
! Logical NOT: negates the truthiness of the operand. !(x < 6) returns false if the condition is true.

13. What is the ternary (?:) operator in JavaScript?

Answer: The ternary operator (also called the conditional operator) is a shorthand way to write a if-else statement. It allows you to perform a quick conditional check and return one of two values based on the result. The syntax is:

condition ? exprIfTrue : exprIfFalse

14. How do you write single-line and multi-line comments in JavaScript?

Answer: In JavaScript, comments are essential for enhancing code readability and maintainability. There are two primary types of comments: single-line comments and multi-line comments.

Single-Line Comments

Single-line comments begin with // and extend to the end of the line. Anything after // on that line is ignored by the JavaScript engine.

Multi-Line Comments

Multi-line comments begin with /* and end with */. Multi-line comments are useful for longer explanations or for commenting out blocks of code.

15. What is a NaN value in JavaScript?

Answer: In JavaScript, NaN stands for Not-a-Number. It is a special value that represents an invalid number or a result that is not a valid numerical operation. You typically encounter NaN when a mathematical operation fails or when attempting to convert a non-numeric value to a number.

16. How do if, else, and else if work in JavaScript?

Answer: In JavaScript, the if, else, and else if statements are used for conditional execution of code, allowing you to run specific blocks of code based on whether a condition is true or false.

if Statement

The if statement checks a condition. If the condition evaluates to true, the code inside the if the block is executed.

Syntax:

if (condition)
{
// Code to execute if the condition is true
}

else Statement

The else statement provides an alternative block of code to run when the if condition is false.

Syntax:

if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}

else if Statement

The else if statement allows you to check multiple conditions. If the first if condition is false, JavaScript evaluates the next else if condition, and so on. If none of the if or else if conditions are true, the else block (if present) will execute.

Syntax:

if (condition1)
{
// Code to execute if condition1 is true
}
else if (condition2)
{
// Code to execute if condition2 is true
}
else
{
// Code to execute if both conditions are false
}

17. What is a switch statement, and when would you use it instead of if?

Answer: A switch statement in JavaScript is used for making decisions based on the value of a variable or expression. It is particularly useful when you have multiple conditions to evaluate against a single variable or expression.

Syntax

The basic syntax of a switch statement is as follows:

switch (expression)
{
case value1: // code block executed if expression matches value1
break;
case value2: // code block executed if expression matches value2
break;
// more cases...
default:
// code block executed if no case matches
}

18. What are the different types of loops in JavaScript?

Answer: JavaScript provides several types of loops to execute code repeatedly based on conditions. Each loop has its own specific use cases depending on the nature of the iteration required.

for Loop

The for loop is used when the number of iterations is known beforehand. It consists of three parts: initialization, condition, and increment/decrement.

Syntax:

for (initialization; condition; increment)
{
// code to be executed
}

While Loop

The while loop continues to execute as long as a specified condition is true. It checks the condition before each iteration.

Syntax:

while (condition)
{
// code to be executed
}

Do...While Loop

Similar to the while loop, but it guarantees that the code block will execute at least once because the condition is checked after the execution.

Syntax

do
{ // code to be executed
} while (condition);

For...In Loop

The for...in loop is used to iterate over the properties of an object. It accesses keys in an object and can also be used with arrays (though not recommended for array iteration).

Syntax

for (let value of iterable)
{
// code to be executed for each value
}

19. What is the difference between while and do...while loops?

Answer: The key differences between while and do...while loops are as follows:

while do... while
Evaluated before executing the loop body. Evaluated after executing the loop body.
May not execute at all if the condition is false initially Always executes at least once

20. How do you create an array in JavaScript?

Answer: In JavaScript, you can create an array using several methods. Here are the most common ways:

1. Using Array Literals:

The simplest and most common way to create an array is using square brackets ([]).

Syntax:

const array = [element1, element2, element3, ...];

2. Using the Array Constructor:

You can also create an array using the Array() constructor, though this is less common than array literals.

Syntax:

const array = new Array(element1, element2, element3, ...);

21. What is the difference between push() and unshift()?

Answer: The push() and unshift() methods in JavaScript are used to add elements to an array, but they differ in where the elements are added:

push() adds elements to the end, while unshift() adds them to the beginning.

22. What is the difference between pop() and shift()?

Answer: The pop() and shift() methods in JavaScript are used to remove elements from an array. pop() removes elements from the end of the array, while shift() removes elements from the beginning.

23. What is an event in JavaScript?

Answer: An event in JavaScript refers to any action or occurrence that happens within the browser or web page, which can be triggered by user interactions or by the browser itself. The common types of events are: Mouse Events, Keyboard Events, Form Events, Window Events

24. How do you select elements using getElementById()?

Answer: The getElementById() method in JavaScript is a widely used function that allows developers to select and manipulate HTML elements based on their unique ID.

Syntax:

document.getElementById('id');

25. How do you use console.log() for debugging?

Answer: console.log() is used to print values to the browser’s console, which helps track the flow of the code and identify issues.

Intermediate Javascript Interview Questions and Answers

1. What is the difference between function declaration and function expression?

Answer: A function declaration defines a named function that can be invoked anywhere in the code, even before the declaration itself. whereas A function expression defines a function that can be either anonymous or named, and it’s assigned to a variable. Function expressions are not hoisted, meaning they can only be called after they are defined.

2. What is an anonymous function?

Answer: An anonymous function in JavaScript is a function that does not have a name. It is typically used as a function expression and is often assigned to a variable. it is useful in scenarios like callbacks, function expressions, or for immediate execution.

Syntax of an Anonymous Function:

const myFunction = function() {
 console.log("This is an anonymous function.");
 }; 

3. Explain arrow functions.

Answer: Arrow functions in JavaScript are a shorter syntax for writing function expressions, introduced in ES6 (ECMAScript 2015). An arrow function uses the => syntax:

const add = (a, b) => {
return a + b;
};

4. What are higher-order functions in JavaScript?

Answer: Higher-order function is defined as functions that either take one or more functions as arguments or return a function as their result. They are used extensively in array manipulation, event handling, and creating more dynamic and modular applications. Common Higher-Order Functions in JavaScript are map(), filter(), reduce().

5. What is a callback function?

Answer: A callback function is a function that is passed as an argument to another function. It provides flexibility and enables you to execute code when certain events or operations are completed.

Example:

function greet(name, callback)
{
console.log("Hello, " + name);
callback();
}
greet("Alice", function(){
console.log("Welcome!");
});

6. What are closures in JavaScript?

Answer: A closure in JavaScript is a feature where a function retains access to variables from its outer (enclosing) function, even after the outer function has completed execution. This allows the inner function to remember and continue accessing variables from the outer function's scope.

Example:

function counter()
{
let count = 0;
return function() {
count++;
console.log(count);
};
}
const increment = counter(); // Creates a closure with `count`
increment(); // Output: 1
increment(); // Output: 2
increment(); // Output: 3

Here:

  • The count variable is preserved across multiple calls to increment() even though the counter function has already finished executing.
  • The inner function maintains access to count, making it behave like a private variable that cannot be modified directly from outside.

7. Explain what an Immediately Invoked Function Expression (IIFE) is.

Answer: An Immediately Invoked Function Expression (IIFE) is a JavaScript function that is defined and executed immediately after its creation.

Example: 

(function()
{
console.log("This is an IIFE!");
})();

8. What is memoization in functions?

Answer: Memoization is a powerful technique that enhances function performance by caching the results of expensive function calls and returning the cached result when the same inputs occur again.

9. How do you create an object using Object.create() in JavaScript?

Answer: The Object.create() method creates a new object using an existing object as its prototype. 

Syntax: 

Object.create(object, properties)

10. How do you iterate over the properties of an object?

Answer: In JavaScript, there are several ways to iterate over the properties of an object. Each method has its specific use cases and functionality. The common ways to iterate over an object’s properties:

const person = {
name: "John",
age: 30,
city: "New York"
};
const entries = Object.entries(person); // Iterating using forEach and Object.entries()
entries.forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});

11. What is object destructuring in JavaScript?

Answer: Object destructuring in JavaScript is a convenient way to extract values from objects and assign them to variables in a concise manner.

Syntax:

const { property1, property2 } = object;

12. How do you merge two objects in JavaScript?

Answer: In JavaScript, you can merge two or more objects in several ways. Here are the common approaches to merge objects:

1. Using the Object.assign() method:

Object.assign() copies properties from one or more source objects to a target object. The target object is the first argument, followed by the source objects.

Syntax:

Object.assign(target, source1, source2, ...); 

2. Using the Spread Operator (...):

The spread operator (...) is a modern and concise way to merge objects, introduced in ES6. It spreads the properties of the source objects into a new object.

Syntax

const mergedObject = { ...object1, ...object2 };

13. What is the difference between map() and forEach()?

Answer: The map() and forEach() methods in JavaScript are both used to iterate over arrays, but they differ in functionality and usage:

  • map() returns a new array with transformed values, while forEach() does not return anything.
  • map() does not mutate the original array while forEach() can mutate the original array.

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

Answer: The key differences between stopPropagation() and preventDefault() are as follows:

preventDefault() stopPropagation()
Prevents the default action of the event Stops the event from propagating (bubbling or capturing)
Used when you want to prevent default behaviors (e.g., form submission) Used when you want to stop the event from reaching other elements.

15. What is the reduce() method in JavaScript?

Answer: The reduce() method in JavaScript is used to accumulate values from an array into a single output value. This can be useful for various operations such as summing numbers, flattening arrays, or transforming data structures.

Syntax:

array.reduce(callback(accumulator, currentValue), initialValue)

16. What is the DOM in JavaScript?

Answer: The Document Object Model (DOM) in JavaScript is an interface that browsers use to represent and interact with HTML and XML documents. It allows JavaScript to access and modify HTML and CSS, enabling changes to the structure, content, and style of a page in response to user interactions.

17. What is callback hell?

Answer: Callback hell refers to a situation in JavaScript where multiple asynchronous operations are nested within each other, leading to complex and deeply indented code structures. This situation typically occurs when developers use callbacks extensively to manage asynchronous tasks. By using Promises or async/await, developers can avoid callback hell.

18. What is the difference between synchronous and asynchronous callbacks?

Answer: Synchronous callbacks execute immediately and block further code execution until completed. In contrast, asynchronous callbacks do not block the execution, allowing the program to continue running.

19. What is a Promise in JavaScript, and what problem does it solve?

Answer: A Promise represents a value that might be available now, later, or never. It provides a cleaner way to handle asynchronous operations compared to callbacks, avoiding callback hell.

20. How do you handle success and failure in a Promise?

Answer: You handle success with the then() method and failure with the catch() method:

myPromise.then(result =>
{
console.log('Success:', result);
}) .catch(error =>
{ console.error('Error:', error);
});

21. What are the three states of a Promise?

Answer: A Promise can be in one of three states:

  • Pending: The initial state, neither fulfilled nor rejected.

  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

22. What is promise chaining?

Answer: Promise chaining is a programming pattern in JavaScript that allows multiple asynchronous operations to be executed in a sequential manner using the .then() method.

23. What is the difference between localStorage and sessionStorage in JavaScript?

Answer: The differences between localStorage and sessionStorage in JavaScript are as follows:

localStorage sessionStorage
Data is shared across all tabs and windows of the same origin Data is specific to the tab or window where it was created.
Used for long-term data storage Used for short-term data storage
Data persists indefinitely until explicitly removed by code Data is cleared when the tab/window is closed

24. How do you select elements in JavaScript?

Answer: You can select DOM elements using methods like:

  • getElementById()
  • querySelector() (for CSS selectors)
  • getElementsByClassName() and others.

25. How do you modify HTML and CSS using JavaScript?

Answer: You can change the inner HTML of an element using innerHTML, and modify styles using the style property. Example:

document.querySelector('div').innerHTML = "Hello"; document.querySelector('div').style.color = "blue";

26. How do you create and remove DOM elements dynamically?

Answer: You can create elements using document.createElement() and append them using appendChild(). Elements can be removed using removeChild().

const newDiv = document.createElement('div');
document.body.appendChild(newDiv);
document.body.removeChild(newDiv); 

Javascript Interview Questions for Senior Developer

1. What is the purpose of the "this" keyword in JavaScript?

Answer: In JavaScript, the this keyword is used to refer to the current context or the object from which a function is being invoked. Its value depends on how and where the function is called. The purpose of this is to allow access to the properties and methods of an object within its own context.Here’s an overview of how this behaves in different contexts:

Context Description
Global Context When this is used in the global scope (outside any function), it refers to the global object (e.g., window in browsers). For example:
javascript console.log(this); // Outputs: Window {...} 
Function Context In a regular function (not a method of an object), this refers to the global object, unless the function is called in strict mode, where it becomes undefined.
javascript function show() { console.log(this); } show(); // Outputs: Window {...} 
Method Context When a function is called as a method of an object, this refers to that object.
javascript const obj = { name: 'Alice', greet: function() { console.log(this.name); } }; obj.greet(); // Outputs: Alice 
Event Handlers In event handlers, this refers to the DOM element that triggered the event. If an arrow function is used, this will refer to the enclosing lexical scope instead.
javascript const button = document.querySelector('button'); button.addEventListener('click', function() { console.log(this); }); // Outputs: <button>...</button> 
Arrow Functions Arrow functions do not have their own this. Instead, they inherit this from the surrounding lexical scope where they were defined.
javascript const obj = { name: 'Alice', greet: () => { console.log(this.name); } }; obj.greet(); // Outputs: undefined (if not in an object) 
Explicit Binding You can explicitly set the value of this using methods like call()apply(), and bind().
call(): Calls a function with a specified this value and arguments.
apply(): Similar to call but takes an array of arguments.
bind(): Returns a new function with a bound this.
javascript function greet() { console.log(`Hello, my name is ${this.name}`); } const person = { name: 'Bob' }; greet.call(person); // Outputs: Hello, my name is Bob 

2. Explain async/await and how they improve asynchronous code.

Answer:  Async/await is a feature in JavaScript that provides a more readable and intuitive way to handle asynchronous code, especially when working with promises. It simplifies the process of writing and managing asynchronous operations, making the code easier to understand and maintain, while avoiding the complexities of using callbacks or promise chaining.

async

When you declare a function with the async keyword, it automatically returns a Promise. If the function returns a value, that value is wrapped in a resolved Promise.

Example:

async function fetchData()
{
return 'data';
}
fetchData().then(data => console.log(data)); // Logs: "data"

await:

The await keyword can only be used inside an async function. It pauses the execution of the function until the Promise is resolved or rejected, allowing for cleaner and more manageable asynchronous code.

Example:

async function fetchData()
{
let data = await someAsyncOperation();
console.log(data);
}
fetchData();

3. How do you handle errors in JavaScript?

Answer: Errors can be caught using try...catch blocks. Example:

try 
{
// Code that may throw an error
} catch (error) {
console.log(error.message); // Handle the error 
}

4. What are JavaScript modules, and how do you import/export them?

Answer: JavaScript modules are a way to split up code into separate files, which makes it easier to manage and reuse. Modules allow developers to keep related code organized, and they enable you to share code across different files by exporting and importing functionality.

Export modules

The export keyword is used to make functions, objects, or variables available for use in other modules. There are two types of exports:

Named Exports: You can export multiple items from a module.

// person.js
 export const name = "Jesse";
 export const age = 40;

Default Exports: You can export a single item as the default export of a module.

// message.js
const message = () => "Hello World!";
export default message;

Importing Modules

To use exported code in another file, you can use the import statement.

Importing Named Exports:

You need to import named exports using curly braces, and you can import multiple items at once.

import { name, age } from './person.js';

Importing Default Exports:

You can import default exports without curly braces, and the imported name can be anything.

import message from './message.js';

5. What is debouncing?

Answer: Debouncing is a programming technique used to improve the performance of web applications by controlling the frequency of function calls. It is particularly useful in scenarios where a function may be triggered multiple times in quick succession, such as resizing the window, scrolling, or typing in an input field.