Question library

JavaScript interview questions and answers

45 JavaScript interview questions with answers: 10 junior, 15 mid-level and 20 senior. Junior answers are free to read.

Junior Mid Senior Updated How these answers are created

* View counts were reset on 18 October 2026, when Interviewplus moved to interviewplus.app. Votes were not affected.

Answer

JavaScript is a high-level, dynamic, interpreted programming language that is commonly used for creating interactive web pages and user interfaces. It is designed to be run on web browsers, but it can also be used on servers and other devices through its various implementations.
Some key features of JavaScript include:
1. Dynamic Typing: JavaScript is a dynamically typed language, meaning that variable types are determined at runtime. This allows for greater flexibility and ease of use, but it also means that type errors can only be caught at runtime.
2. Object-Oriented Programming (OOP): JavaScript supports OOP principles such as encapsulation, inheritance, and polymorphism. Objects in JavaScript can be created using either constructor functions or object literals.
3. Functions as First-Class Citizens: Functions in JavaScript are treated as first-class citizens, meaning that they can be assigned to variables, passed as arguments to other functions, and returned as values from functions.
4. Asynchronous Programming: JavaScript supports asynchronous programming, which allows code to run in the background without blocking the main thread. This is commonly used for tasks such as fetching data from a server or animating user interfaces.
5. DOM Manipulation: JavaScript can manipulate the Document Object Model (DOM) of a web page, allowing it to change the content and style of the page in response to user interactions or other events.
6. Event-Driven Programming: JavaScript is event-driven, meaning that it can respond to user events such as clicks, scrolls, and key presses. This allows for the creation of interactive web applications that respond to user input in real-time.
Overall, JavaScript is a powerful and versatile language that is widely used in web development due to its flexibility, ease of use, and extensive ecosystem of libraries and frameworks.

Answer

In JavaScript, var, let, and const are all used for declaring variables, but they have some important differences in their behavior.
var is the oldest keyword for declaring variables in JavaScript. It has function scope, meaning that a variable declared with var inside a function is only accessible within that function. Variables declared with var can also be hoisted, which means that they are moved to the top of their scope and can be accessed before they are declared.
let and const were introduced in ECMAScript 6 and have block scope, meaning that a variable declared with let or const inside a block (such as a loop or if statement) is only accessible within that block. Unlike var, variables declared with let and const are not hoisted.
The main difference between let and const is that let variables can be reassigned to a new value, while const variables cannot be reassigned. This makes const useful for declaring variables that should never change, such as constants or configuration values.
Here's an example to illustrate the differences between var, let, and const:

function example() {
  var x = 1;
  let y = 2;
  const z = 3;

  if (true) {
    var x = 10; // This will overwrite the previous value of x
    let y = 20; // This creates a new variable y with block scope
    const z = 30; // This creates a new variable z with block scope

    console.log(x); // Output: 10
    console.log(y); // Output: 20
    console.log(z); // Output: 30
  }

  console.log(x); // Output: 10
  console.log(y); // Output: 2
  console.log(z); // Output: 3
}

example();

In this example, var x is accessible throughout the function, even within the if block, because var has function scope. let y and const z are only accessible within their respective blocks because they have block scope. The if block creates new variables y and z with block scope, while var x overwrites the previous value of x because it has function scope. Finally, outside the if block, var x retains its new value of 10, while let y retains its original value of 2, and const z retains its original value of 3.

Answer

In JavaScript, == and === are both comparison operators, but they have different behaviors.
The == operator is the equality operator, and it compares two values for equality after converting them to a common type. If the two values have different types, JavaScript will attempt to convert one or both of the values to a common type before making the comparison. This can lead to unexpected behavior, especially when comparing values of different types.
For example:

console.log(5 == "5"); // Output: true
console.log(false == 0); // Output: true
console.log(null == undefined); // Output: true

In these examples, JavaScript is converting the values to a common type before making the comparison. In the first example, the string "5" is converted to the number 5 before the comparison. In the second example, the boolean value false is converted to the number 0 before the comparison. In the third example, null and undefined are both considered to be equal when using the equality operator.
The === operator is the strict equality operator, and it compares two values for equality without converting them to a common type. If the two values have different types, the comparison will return false. This is generally considered to be a safer and more predictable way to compare values.
For example:

console.log(5 === "5"); // Output: false
console.log(false === 0); // Output: false
console.log(null === undefined); // Output: false

In these examples, the strict equality operator returns false because the values have different types.
In general, it's recommended to use the strict equality operator === instead of the equality operator == whenever possible, to avoid unexpected behavior and make code easier to understand.

Answer

In JavaScript, there are two main ways to define a function: function declaration and function expression.
A function declaration defines a named function using the function keyword, followed by the name of the function and a pair of parentheses, like this:

function add(x, y) {
  return x + y;
}

A function declaration is "hoisted" to the top of its scope, which means that it can be called from anywhere in the scope, even before it is defined.
A function expression defines a function as part of an expression, usually by assigning it to a variable. For example:

const add = function(x, y) {
  return x + y;
}

In this case, the function is defined as an anonymous function, and then assigned to a variable called add. Function expressions are not hoisted, which means that they cannot be called before they are defined.
There are a few other differences between function declarations and function expressions:
- Function declarations can only be defined at the top level of a block or function, while function expressions can be defined anywhere that an expression is allowed.- Function declarations create a new symbol in the current scope, while function expressions create a new variable with the function as its value.- Function declarations have a name that can be used inside the function, while function expressions can be anonymous or named.
Here's an example to illustrate the differences:

// Function declaration
console.log(add(2, 3)); // Output: 5

function add(x, y) {
  return x + y;
}

// Function expression
const subtract = function(x, y) {
  return x - y;
}

console.log(subtract(5, 2)); // Output: 3

In this example, we can see that the function declaration for add is hoisted to the top of the scope, so it can be called before it is defined. The function expression for subtract is assigned to a variable and cannot be called before it is defined.

Answer

Here's an example of a JavaScript program that calculates the first n Fibonacci numbers using loops and functions:

function fibonacci(n) {
  let fib = [0, 1];
  for (let i = 2; i < n; i++) {
    fib[i] = fib[i - 1] + fib[i - 2];
  }
  return fib;
}

let n = 10;
let result = fibonacci(n);
console.log(`The first ${n} Fibonacci numbers are: ${result}`);

In this program, we define a function called fibonacci that takes an argument n and returns an array of the first n Fibonacci numbers. The function initializes an array called fib with the first two numbers in the sequence (0 and 1), and then uses a for loop to calculate the remaining numbers. The loop starts at 2 (since we already have the first two numbers), and calculates each subsequent number by adding the previous two numbers in the sequence.
We then call the fibonacci function with an argument of 10, which will return an array containing the first 10 Fibonacci numbers. Finally, we log a message to the console displaying the result.

Answer

In JavaScript, null and undefined are both special values that represent the absence of a value, but they are used in slightly different ways.
undefined is a primitive value that is automatically assigned to a variable that has not been initialized or to a function that does not return a value. For example:

let myVariable;
console.log(myVariable); // Output: undefined

function myFunction() {
  // This function does not return a value
}

console.log(myFunction()); // Output: undefined

In these examples, myVariable is declared but not initialized, so it has the value of undefined. The myFunction function does not return a value, so it also has the value of undefined.
null, on the other hand, is an explicit value that represents the absence of any object value. It is typically used when a variable or property should have an explicit "no value" state. For example:

let myVariable = null;
console.log(myVariable); // Output: null

In this example, we're explicitly setting myVariable to null, which represents an absence of any object value.
Here are some additional differences between null and undefined:
- undefined is a primitive value, while null is an object.- undefined is the default value of uninitialized variables, while null must be assigned explicitly.- undefined is used when a variable or property has not been assigned a value, while null is used to represent an intentional absence of any object value.
It's worth noting that null and undefined are both "falsy" values in JavaScript, which means that they will be treated as false in a boolean context.

Answer

Event bubbling is a mechanism in JavaScript where events triggered on a nested or child element "bubble up" through its parent elements in the DOM tree, eventually reaching the topmost ancestor element. 
Here's how it works: when an event is triggered on an element, such as a click event on a button, that event is first handled by the innermost element that was clicked. This is called the "target" element. Then, the event bubbles up through all of the ancestor elements of the target element, one level at a time, until it reaches the topmost ancestor element. This is called the "capturing" phase. Finally, the event triggers on the topmost ancestor element, and then bubbles down through all of the ancestor elements back to the target element. This is called the "bubbling" phase. 
During the bubbling phase, each ancestor element can choose to handle the event if it wants to. This means that a single event on a child element can trigger multiple event handlers on its parent elements. 
Here's an example to illustrate event bubbling:

<div id="outer">
  <div id="middle">
    <button id="inner">Click me</button>
  </div>
</div>

In this example, clicking the "Click me" button will trigger a click event on the button element first, and then that event will bubble up through the middle div and finally the outer div.
You can use the addEventListener method to attach event listeners to elements, and you can use the event.stopPropagation() method to stop the event from bubbling up to parent elements.
Event bubbling can be a powerful tool for handling events in complex web applications, but it can also be a source of bugs if you're not careful. Understanding how it works is an important part of writing robust JavaScript code.

Answer

In JavaScript, you can handle errors using try-catch blocks. 
A try-catch block is a structure that lets you attempt a block of code and catch any errors that might occur. Here's how it works:
1. Wrap the block of code that might throw an error in a try block.
2. If an error occurs inside the try block, execution will immediately jump to the corresponding catch block.
3. The catch block will receive an error object that contains information about the error, such as its name and message.
4. You can then use the information in the error object to handle the error in an appropriate way, such as logging an error message or displaying a user-friendly error message.
Here's an example:

try {
  // Code that might throw an error
  const result = someFunctionThatMightThrowAnError();
  console.log(result);
} catch (error) {
  // Handle the error
  console.error('An error occurred:', error);
}

In this example, we're wrapping a call to someFunctionThatMightThrowAnError in a try block. If an error occurs inside that function, execution will jump to the corresponding catch block, which will log an error message to the console.
It's important to note that try-catch blocks should only be used for handling expected errors, such as errors that might occur due to user input or network connectivity issues. Unexpected errors, such as syntax errors or type errors, should be caught and fixed during development.
In addition to try-catch blocks, you can also use the finally block to run code that should always execute, regardless of whether an error occurs or not. The finally block runs after the try and catch blocks, and can be useful for performing cleanup tasks or releasing resources.
Here's an example:

try {
  // Code that might throw an error
  const result = someFunctionThatMightThrowAnError();
  console.log(result);
} catch (error) {
  // Handle the error
  console.error('An error occurred:', error);
} finally {
  // Perform cleanup tasks
  console.log('Done');
}

In this example, the finally block will always execute, even if an error occurs or the catch block is executed.

Answer

Here's an example of a JavaScript-based game, specifically a simple memory matching game:
HTML:

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Memory Matching Game</title>
	<link rel="stylesheet" href="style.css">
</head>
<body>
	<div id="game-board">
		<div class="card"></div>
		<div class="card"></div>
		<div class="card"></div>
		<div class="card"></div>
		<div class="card"></div>
		<div class="card"></div>
		<div class="card"></div>
		<div class="card"></div>
	</div>
	<script src="app.js"></script>
</body>
</html>

CSS:

#game-board {
	display: flex;
	flex-wrap: wrap;
	width: 400px;
	margin: 0 auto;
}

.card {
	width: 50px;
	height: 50px;
	margin: 10px;
	background-color: #ccc;
	cursor: pointer;
}

JavaScript:

const cards = document.querySelectorAll('.card');

let hasFlippedCard = false;
let lockBoard = false;
let firstCard, secondCard;

function flipCard() {
	if (lockBoard) return;
	if (this === firstCard) return;

	this.classList.add('flip');

	if (!hasFlippedCard) {
		hasFlippedCard = true;
		firstCard = this;
		return;
	}

	secondCard = this;

	checkForMatch();
}

function checkForMatch() {
	let isMatch = firstCard.dataset.framework === secondCard.dataset.framework;

	isMatch ? disableCards() : unflipCards();
}

function disableCards() {
	firstCard.removeEventListener('click', flipCard);
	secondCard.removeEventListener('click', flipCard);

	resetBoard();
}

function unflipCards() {
	lockBoard = true;

	setTimeout(() => {
		firstCard.classList.remove('flip');
		secondCard.classList.remove('flip');

		resetBoard();
	}, 1000);
}

function resetBoard() {
	[hasFlippedCard, lockBoard] = [false, false];
	[firstCard, secondCard] = [null, null];
}

(function shuffle() {
	cards.forEach(card => {
		let randomPos = Math.floor(Math.random() * 8);
		card.style.order = randomPos;
	});
})();

cards.forEach(card => card.addEventListener('click', flipCard));

This game involves clicking on two cards to flip them over and see if they match. If they do match, the cards stay flipped over, and if they don't match, they flip back over. The game continues until all cards are matched. The JavaScript code above handles the game logic, including shuffling the cards, checking for matches, and disabling or flipping back over the cards as needed.

Answer

In JavaScript, synchronous programming is the traditional programming model in which code is executed sequentially, one line at a time. This means that each line of code has to finish executing before the next line can begin executing.
In contrast, asynchronous programming is a model in which code is executed non-sequentially, allowing multiple operations to be performed simultaneously. In asynchronous programming, a task can be started and the program can continue to run while the task is being completed. When the task is finished, a callback function is called to handle the result.
Asynchronous programming is often used in situations where a task may take a long time to complete, such as making a network request or reading a large file. Instead of waiting for the task to complete before moving on to the next line of code, the program can continue running, allowing the user to interact with the application while the task is being performed.
Here's an example of synchronous code:

console.log('Line 1');
console.log('Line 2');
console.log('Line 3');

In this code, each line will be executed one after the other, in the order they appear.
Here's an example of asynchronous code:

console.log('Line 1');
setTimeout(() => {
  console.log('Line 2');
}, 1000);
console.log('Line 3');

In this code, the setTimeout function is used to delay the execution of the callback function by one second. The console.log('Line 3') statement will be executed before the callback function, because the delay ensures that the callback function is not executed immediately.
In summary, synchronous programming executes code sequentially, one line at a time, while asynchronous programming allows for non-sequential execution, enabling tasks to be performed simultaneously, with the help of callbacks, promises or async/await functions.

Answer preview

Sure, here's an example of a JavaScript-based web application that uses the GitHub API to display and search for user repositories:

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In JavaScript, you can create a class using the `class` keyword. Here's an example: In this example, we've defined a `Person` class with a constructor that takes `name` and `age` parameters and sets them as properties of the class. We've also defined a `sayHello` method that logs a greeting message to the console. To…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In JavaScript, synchronous code executes in a single sequence, where each statement waits for the previous statement to finish before executing. This means that if there is a long-running task, such as a network request or a heavy computation, it will block the execution of subsequent code until it completes. For…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Promises in JavaScript are a way to handle asynchronous code that allows you to avoid using nested callbacks or callback hell. A Promise represents a value that may not be available yet, but will be resolved at some point in the future, either successfully with a result, or with an error. A Promise has three states…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In JavaScript, `call`, `apply`, and `bind` are methods that can be used to set the `this` value of a function explicitly. They are useful in situations where you want to invoke a function with a different `this` value than it was originally defined with, or when you want to pass arguments to a function in a specific…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In JavaScript, exceptions are handled using the `try-catch` statement. The `try` block contains the code that might throw an exception, and the `catch` block is executed if an exception is thrown. Here's an example: In this example, we use a `try` block to wrap the code that might throw an exception. We call a…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Sure, here is an example of a simple calculator implemented in JavaScript: This calculator uses four functions to perform the four basic arithmetic operations (addition, subtraction, multiplication, and division). Each function retrieves the two input values, checks that they are valid numbers, and then performs the…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In JavaScript, a callback function is a function that is passed as an argument to another function and is called when a certain event or condition occurs. Callback functions are commonly used in asynchronous programming to handle the result of an operation that may take some time to complete. Here's an example of how…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

A higher-order function is a function that takes one or more functions as arguments or returns a function as its result. In other words, a higher-order function operates on other functions, either by accepting them as arguments or by returning them as values. Here's an example of a higher-order function in JavaScript…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In terms of scope, `var`, `let`, and `const` behave differently in JavaScript. `var` has function scope, which means that it is scoped to the function it is declared in, or to the global scope if it is declared outside of any function. This means that `var` variables can be accessed from anywhere within the function…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

The `map()` method is a built-in method in JavaScript that is used to transform elements of an array. The `map()` method creates a new array with the same length as the original array and applies a function to each element of the original array. The function returns a transformed value, and this transformed value is…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In JavaScript, both `forEach()` and `map()` methods are used to iterate over an array and apply a function to each element. However, there are some key differences between the two methods. 1. Return value: `forEach()` method does not return a new array. It simply executes a provided function once for each array…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Here are some ways to improve the performance of JavaScript code: 1. Use efficient algorithms and data structures: Use the most efficient algorithms and data structures for your use case to reduce the time and space complexity of your code. 2. Minimize DOM manipulation: Accessing and manipulating the DOM is an…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Sure, here is an example of creating a bar chart using JavaScript and the Chart.js library: First, include the Chart.js library in your HTML file: Then, create a JavaScript file and write the following code to create a bar chart: This code defines a bar chart with seven labels and one dataset. You can customize the…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Asynchronous code is handled in JavaScript using callbacks, promises, and async/await. 1. Callbacks: A callback is a function that is passed as an argument to another function and is executed when the first function has completed. Callbacks are a common way to handle asynchronous code in JavaScript. For example: 2…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Here's an example of how to create a form using React that includes validation, auto-completion, and real-time feedback: In this example, we use the useState hook to manage the state of the input value and the error. The handleSubmit function is called when the form is submitted, and it checks if the input value is…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Yes, I can explain the difference between `let`, `const`, and `var` in JavaScript. 1. `var`: `var` is a keyword used to declare variables in JavaScript. It has function scope, meaning that variables declared with `var` are accessible throughout the function in which they are declared. If a variable declared with `var`…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

There are several ways to optimize the performance of a JavaScript application: 1. Minimize HTTP requests: One of the most important factors in web performance is reducing the number of HTTP requests. You can do this by minimizing the number of external resources (e.g. images, stylesheets, scripts) on your page and…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Here's an example of how you can use JavaScript to manipulate the DOM and modify the appearance and behavior of a web page: In this example, we use JavaScript to manipulate the DOM and modify the appearance and behavior of a web page. Specifically, we create a simple box-drawing application that allows the user to add…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

The event loop is an essential part of the JavaScript runtime, and it's responsible for handling the execution of code in a non-blocking way. While there are already built-in event loops in JavaScript environments, like the browser or Node.js, it's possible to create a simplified implementation of an event loop in…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In JavaScript, errors can be handled using the try-catch-finally statements. The try block contains the code that may throw an exception, and the catch block contains the code that handles the exception. The finally block contains the code that executes regardless of whether an exception was thrown or not. Here's an…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Yes, I can explain how closures work in JavaScript. A closure is a function that has access to variables defined in its outer (enclosing) function, even after the outer function has returned. This is possible because the inner function preserves the environment in which it was created, including the values of all…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

To implement a callback function in JavaScript, you can follow these steps: 1. Define a function that takes a callback function as a parameter. 2. Within the function, execute the callback function at the appropriate time, passing in any necessary arguments. Here's an example that demonstrates how to implement a…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

JavaScript has a garbage collector that automatically frees up memory that is no longer needed. However, there are a few things you can do to help manage memory usage in your JavaScript code: 1. Avoid creating unnecessary objects: Every object created in your code consumes memory, so try to avoid creating objects that…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

First, you'll need to download the lightbox library and add it to your HTML file: Next, create a container element for your images: In this example, we're using thumbnail images that link to the full-size images with the data-lightbox attribute. Finally, initialize the lightbox plugin: This code will initialize the…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Debouncing is a technique used to limit the rate at which a function is called. It can be useful for functions that are triggered by events that can happen frequently, such as window resizing or scrolling. To implement a debounce function in JavaScript, you can use the `setTimeout()` method to delay the execution of…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Yes, I can explain how promises work in JavaScript. Promises in JavaScript are a way to handle asynchronous operations such as fetching data from an API, making database queries, or reading files. A promise represents a value that may not be available yet, but will be resolved in the future. A promise has three…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Sure, here's an example of how to implement AJAX functionality in a JavaScript-based web app: In this example, we have a web page with a button that, when clicked, retrieves a random quote from an API using AJAX. Here's how it works: 1. We create a button element with an onclick attribute that calls the getQuote…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Yes, I can explain how the prototype chain works in JavaScript. In JavaScript, every object has a prototype, which is either another object or null. When a property is accessed on an object, JavaScript first looks for the property on the object itself. If the property is not found on the object, JavaScript then looks…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In JavaScript, a recursive function is a function that calls itself within its definition. Here's an example of a recursive function that calculates the factorial of a number: In this example, the `factorial` function takes an argument `n`. If `n` is either 0 or 1, the function returns 1. Otherwise, the function calls…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Event bubbling is a phenomenon in JavaScript where an event occurring in a nested element will "bubble up" to its parent and ancestor elements, triggering their corresponding event listeners as well. To handle event bubbling in JavaScript, you can use the `event.stopPropagation()` method. Here is an example of how to…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Cross-Site Scripting (XSS) is a type of security vulnerability that allows attackers to inject malicious scripts into a web page viewed by other users. To prevent XSS attacks in JavaScript, you can follow these best practices: 1. Sanitize User Input: Ensure that all user input is properly validated and sanitized on…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Yes, I can.  `map`, `filter`, and `reduce` are three commonly used higher-order functions in JavaScript that allow you to work with arrays and transform them into new arrays or values. - `map` is used to transform an array by creating a new array of the same length with each element transformed by a callback function…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Working with dates and times is a common task in JavaScript. JavaScript provides a built-in `Date` object that allows you to work with dates and times. Here are some ways to handle dates and times in JavaScript: 1. Creating a `Date` object: To create a new `Date` object, you can call the `Date` constructor with or…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Certainly! Here's an example JavaScript program that performs various string manipulations: In this example, we start with the string "Hello, World!" and perform various operations on it, such as getting the length, converting to uppercase and lowercase, extracting a substring, splitting into an array, concatenating…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

More practice

Go further with JavaScript

JavaScript code challenges

10 challenges with answers

Behavioral Questions

10 questions with answers

Cultural Fit Questions

10 questions with answers

Competency-Based Questions

10 questions with answers

Motivational Questions

10 questions with answers

Communication Skills Questions

10 questions with answers

Scenario-Based Questions

10 questions with answers

Problem-Solving and Analytical Questions

10 questions with answers

Ethical and Integrity Questions

10 questions with answers

Industry-Specific Questions

10 questions with answers

Leadership and Management Questions

10 questions with answers

Personal Questions

10 questions with answers

About this topic

JavaScript interview questions and answers

This page lists 45 JavaScript interview questions with answers, ordered from junior to senior level. Commonly asked questions include "What is JavaScript and what are its features?", "What is the difference between var, let, and const keywords in JavaScript?" and "What is the difference between == and === operators in JavaScript?".

Other frequently asked questions include "Write a JavaScript program that uses loops, conditionals, and functions to perform a complex operation, such as calculating Fibonacci numbers, finding the largest prime factor, or solving a quadratic equation.", "What is the difference between null and undefined in JavaScript?" and "Develop a JavaScript-based web application that uses APIs, such as Google Maps, Twitter, or GitHub, to display and manipulate data, including features such as authentication, error handling, and asynchronous processing.". Review each answer and consider how you would adapt it to your own experience.

Practise JavaScript in a mock interview

Answer questions one at a time and receive a score with written feedback on each answer.

Start a mock interview

Reviews and comments