Other Guides
In this article
Top 80 JavaScript Coding Interview Questions and Answers

Just like its ecosystem, the world of JavaScript coding interview questions is constantly evolving. As the wonderful programming language that it is, JavaScript is used to create everything from dynamic web pages to complex web servers.
If you’re looking for a JavaScript developer role, once you have a solid knowledge of the language (our JavaScript roadmap is a great place to get started), being prepared for these interviews is crucial to your success. And if you’re a hiring manager, having a great set of questions is just as critical.
In this article, you’ll find a very detailed list of questions designed to test a developer’s practical skills in JavaScript.
Getting Ready for the Interview
Before diving into the questions, it’s important to understand what interviewers are looking for.
They want to see how you solve problems, how you face the unknown, and the thought process behind your solutions.
They’ll want to understand how you think about data structures and how you approach real-world scenarios. How do you apply those theoretical tools to solve actual problems?
On top of that, remember to review your basic JavaScript concepts and practice writing clean, efficient code. In the end, you’ll be doing that every day.
You should be comfortable with everything from the const
keyword to how a callback function works. Remember: don't just memorize solutions; understand the core principles.
Test yourself with Flashcards
You can either use these flashcards or jump to the questions list section below to see them in a list format.
What is the difference between var, let, and const?
var
has a global scope or function scope; let
and const
are block-scoped.
var
can be re-declared and updated, let
can be updated but not re-declared.
Finally, const
cannot be re-declared or updated, that’s why they’re called “constants”.
Questions List
If you prefer to see the questions in a list format, you can find them below.
Beginner questions
What is the difference between var, let, and const?
var
has a global scope or function scope; let
and const
are block-scoped.
var
can be re-declared and updated, let
can be updated but not re-declared.
Finally, const
cannot be re-declared or updated, that’s why they’re called “constants”.
Write a function sumArray(arr) that returns the sum of all the elements in an input array.
You can use the reduce
method for this:
This method will apply the “accumulator” function to every element of the array, receiving the current accumulated value (the result from the last call of the function) as the first parameter and the current value being processed as the second one. The “0” in the above code simply defines the initial value for the accumulator variable.
How do you check if a given string is a palindrome? Write a function isPalindrome to demonstrate.
A simple isPalindrome
function could take a given string, reverse it, and compare it to the original.
Since there is no direct way to reverse a string in JavaScript, what we’re doing is turning the string into an array of characters and reversing that. We then join all those values into a single string to compare it with the original input.
Explain type coercion in JavaScript. Give an example.
Type coercion is JavaScript’s automatic conversion of values from one data type to another.
For example, '5' + 5
results in '55'
, as the number 5 is coerced into a string when trying to add a number and a string.
Write a function that reverses a given string. A simple function reversestring should suffice.
You can write a simple reversestring
function like this:
You first split the string into an array of characters, reverse it, and then re-join all characters together. The resulting string is the reversed version of the original one.
How do you find the maximum difference between any two elements in an input array?
You can solve this one by iterating over the input array and calculating the max and min values at the same time. At the end, you can return the difference between those values.
Here’s a sample implementation:
Write a function that checks if a given number is prime. Name your function isprime.
A function isprime
checks if a number is divisible by any integer from 2 up to the square root of the number. If it finds one, it should return false. Here’s a potential implementation for this function:
Given a var c = 10 in the global scope, what happens if you declare var c = 20 inside a function?
The var c = 20
inside the function will be locally scoped, so the variable in the global scope will remain 10.
How do you check if a data type is an object type?
You can use typeof obj === 'object' && obj !== null
.
The null
check is important because typeof null
also returns 'object'
.
Write a function factorial(n) to calculate the factorial of a number using a recursive function.
A recursive function is one that calls itself, and we can write a function that follows this principle and calculates the factorial of a number, like this:
How would you iterate over all elements inside of an array and add them to a new empty array?
You would use a for
loop. For each of the elements, you would use newArray.push(element)
to add it to a new empty array.
Explain the difference between null and undefined.
These two terms are usually confused with each other.
undefined
means a variable has been declared but not assigned a value. null
is a value that can be assigned to a variable to explicitly indicate a non-value or empty string.
How would you write a function removeFalsyValues(arr) that removes falsy values from an array?
Falsy values are values that, once coerced, will evaluate to “false”, such as 0 or an empty array.
A removeFalsyValues
function can be a simple function that uses the filter
method:
What are the different ways to declare a function in JavaScript?
There are three main ways to declare a function in JavaScript:
As a function declaration with the
function
keyword:function myFunciton(..) {...}
As an arrow function:
const myFunction = () => {}
Using the Function object:
const myFunction = new Function(...)
Write a function that returns the Fibonacci sequence up to a certain number.
One potential implementation of this function could look like this:
How can you convert an array of objects into a single object?
You can use the reduce()
method to convert an array of objects into a single object. This approach is very effective because it iterates over the array and accumulates a single value (in this case, a new object).
The reducer function takes two arguments: the accumulator and the current item. You build the final object by adding a new key-value pair for each item in the original array.
This method is concise and is often preferred in modern JavaScript.
Let’s take a look at a potential implementation:
In this approach, the reduce()
method iterates over the array. The first argument is a function that takes the accumulator and the current item. The second argument {}
is the initial value of our accumulator, an empty object.
On every iteration, we get the key and value from the current item (assuming each item has a unique id
and a value
property), and we add a new property to the accumulator with the current item's key and value.
Explain the purpose of a callback function.
A callback function is a JavaScript function that's passed as an argument to another function. The purpose is to have the outer function execute the callback function at a specific point in time or after a particular action is completed, usually an asynchronous one.
This pattern is one of the key patterns in asynchronous JavaScript programming, allowing blocking operations to be executed without blocking the rest of your code (operations like I/O reads, external API calls, etc).
What is the difference between map, filter, and reduce?
map
creates a new array by applying a function (usually a transformation) to each element of the original array.
filter
creates a new array containing only array elements that pass a test (executed by a function passed as a parameter).
reduce
reduces all the elements of an array to a single value.
How do you find the unique elements in an array with duplicate elements? Write a function removeDuplicates(arr) that does this.
A removeDuplicates
function can benefit from the concept of a Set
, which doesn’t allow for duplicate values inside it.
This function initializes a new Set
with the values of the array, by default limiting its content to unique values and then returns a newly formed array using the spread operator (the “...”)
Write a function areAnagrams(str1, str2) that checks if two strings are anagrams of each other.
An areAnagrams
function should check if the sorted versions of two strings are identical.
This way you avoid having to iterate over the characters, simply sort both of them and check the results.
What is the spread operator, and when is it useful?
The spread operator (...
) expands an iterable (like an array) into its individual elements. It's useful for merging arrays or creating copies (as seen in action in question #19).
Write a function to find the largest number in a mixed input array of numbers and strings.
You can use the filter
method to create a new array with only numbers. Then, use return Math.max(...numbers)
to find the largest number. Here we’re using the spread operator again to provide the values of the array as individual parameters of the Math.max
method.
Explain Hoisting in JavaScript.
In JavaScript, hoisting is a mechanism where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed. This means you can use a variable or call a function before it's "officially" declared in your code.
That said, it’s important to understand a very specific detail: only the declarations are hoisted, not the initializations.
For instance, a variable declared with var
can be "used" before its declaration, but its value will be undefined
until the code reaches the line where it's assigned. This is a common source of bugs in javascript programming.
On the other hand, let
and const
declarations are also hoisted, but they exist in a "temporal dead zone" from the start of the block until they are declared, and attempting to access them will throw an error. This behavior makes let
and const
safer and more predictable.
How do you merge two arrays into a single array without using concat()? Write a function called mergeArrays.
A mergeArrays
function can use the spread operator:
This way, the content of both arrays is spread as individual values inside the new array, no need to iterate manually over the arrays or anything.
How do you stringify a JavaScript object into a JSON string?
You use JSON.stringify(obj)
to convert a JavaScript object or value to a JSON string.
How do you create an empty string?
You can declare a variable and assign it ""
or use String()
.
Write a function converts(arr) that converts an array of strings to a single string separated by spaces.
A converts
function can be written like this:
How would you get a new array from an original array with all elements doubled?
To solve this, you can use a map
method call like this:
The map
method returns a new array by default, so you can solve both problems at the same time.
How can you check if an array includes a specific element?
You can use the includes()
method, which is a simple function that returns true
or false
.
What is a JavaScript function?
A JavaScript function is a block of code designed to perform a particular task. It can be called repeatedly throughout your code..
Mid-Level questions
How do you implement a function to debounce a series of function calls?
A debounce function is a JavaScript function that limits the rate at which another function can be called.
It typically takes advantage of both the setTimeout
and clearTimeout
functions to prevent a series of function calls from all firing at once.
What is the event loop, and how does it relate to asynchronous JavaScript?
The event loop is a crucial part of the JavaScript runtime architecture, it helps to handle asynchronous operations.
The event loop constantly checks if the call stack is empty and pushes tasks from the task queue onto it.
Explain the difference between a function declaration and a function expression.
They’re both ways for you to define a function, however:
A function declaration is hoisted, meaning you can call it before it is declared.
A function expression, on the other hand, is not hoisted, so you must define it before you can call it.
How does the this keyword work in a regular JavaScript function versus an arrow function?
A regular JavaScript function sets its own this
keyword based on how it's called, and you can use it to reference itself. An arrow function, however, does not have its own this
keyword; it inherits its scope (what the this
keyword references) from the enclosing scope.
How would you create a private variable using a JavaScript function? Show a function that returns a function or object with methods.
You can use a closure to achieve this. A function that returns a function or an object with a method can access a variable from its parent scope.
Write a function that takes an obj and a key, and returns the value of that key.
Explain Closures and provide an example of where they might be used in javascript programming.
A closure is a special kind of function that "remembers" the environment in which it was created. This environment includes the local variables of its parent function.
This means that even after the parent function has completed its execution, the inner function can still access and use the variables from the parent's scope.
This is a fundamental concept in JavaScript and is used for things like creating private variables and implementing data encapsulation.
What is the spread operator vs the rest parameter?
The spread operator expands an iterable into a list of individual elements, while the rest parameter gathers a variable number of arguments into a single array. The latter is used to define functions with a variable number of parameters.
How do you implement a deep copy of an object? Explain why a shallow copy can be problematic.
To make a deep copy of an object, you can use JSON.parse(JSON.stringify(obj))
.
A shallow copy is problematic because it only copies the top-level properties and still points to the same nested objects as the original array.
What is a callback function? Explain callback hell and a solution to avoid it.
A callback function is a function that gets passed as a parameter to an asynchronous function. Once the asynchronous operation ends, the callback function gets executed.
Callback hell happens when the written code ends up being a deeply nested, unreadable structure of callback functions, often resulting from multiple asynchronous operations, one calling the other from inside its callbacks.
The solution is to use Promises or async/await.
How do you implement a custom Promise.all()?
You write a function that returns a new Promise. Inside, you iterate through the promises, and when all of them have resolved, you resolve the main Promise with the results.
Write a function function multiply(a, b) that takes two parameters and returns their product.
A simple function multiply(a, b)
can be written as const multiply = (a, b) => a * b;
How do you implement a throttle function?
A throttle function ensures a JavaScript function is called at most once per a specified time period. This is often implemented using a timestamp or a flag.
Explain the difference between call(), apply(), and bind().
All three methods change the this
context of a JavaScript function. call()
and apply()
execute the function immediately. call()
takes arguments separately, while apply()
takes them as an input array (particularly useful when you have a dynamic list of values to pass as parameters).
Finally, bind()
returns a new function with the this
context permanently bound to something else.
Write a function that returns a new array with the first five elements of a larger array.
A function that takes an input array and returns the first 5 elements can be written like:
How do you create a function that takes a string of words and returns a reversed array of those words?
Given const words = "hello world"
, you can return words.split(' ').reverse();
How would you handle errors in a chain of Promises?
You can use the .catch()
method at the end of the Promise chain to catch any errors.
Explain the difference between == and ===.
The key difference between ==
and ===
in JavaScript is that ==
checks for value equality (meaning the referenced values are the same), while ===
checks for both value and type equality. The first one will coerce the types if they’re not the same, while the latter will not.
Write a function sumAll(arr) that takes an input array of numbers and returns their sum using the reduce method.
Here’s a sample code that solves this problem:
What is the difference between localStorage, sessionStorage, and cookies?
localStorage
and sessionStorage
store key/value pairs on the client side. The main difference between them is that localStorage
persists even after the browser is closed, while sessionStorage
is cleared.
Then you have cookies, they are sent with every HTTP request to the server, and have a limited size.
How do you implement a Memoization decorator?
You write a function that uses a cache to store the results of previous function calls and returns a function with the cached logic. The cache can be a simple object.
How do you create an object without a prototype?
You can use Object.create(null)
. This creates an object without a prototype chain, which can prevent unexpected behavior.
Write a function that can be used to merge an original array with a new array while avoiding duplicate elements.
You can use a Set to handle duplicate elements and the spread operator to combine the arrays.
How do you get the type of a variable in JavaScript?
Although JavaScript is not a strongly typed language, you can still get the type of a variable by using the typeof
operator.
Explain why JavaScript is a single-threaded programming language.
JavaScript is a single-threaded language because it has a single call stack and a single memory heap. This means it can only execute one task at a time.
What are Higher-Order functions?
Higher-order functions are functions that can either accept other functions as arguments or return functions.
How would you determine if two objects are deeply equal?
Determining if two objects are deeply equal is a common issue in JavaScript programming because the ===
operator only checks if they are the exact same object in memory, not if their contents are identical (but are 2 different instances of the same type of object).
You can use the ===
operator if it’s true, then it’s the same object, which means they’re clearly deeply equal.
You can also check if only one of the objects is null, which would mean they clearly aren’t deeply equal.
Finally, you’ll want to get the list of keys for the objects, and iterate over them, recursively calling the same function to calculate each sub-tree’s deep equality.
Write a function function sum(a, b) that takes two parameters and returns their sum.
A function that function adds two numbers could look like this::
How would you get an empty array?
You can use []
or new Array()
.
Write a function that takes an array of numbers and sorts it in descending order.
Advanced-level questions
Explain how Prototypal Inheritance works in JavaScript.
Prototypal inheritance is a way of creating inheritance in JavaScript.
Every object has a prototype object, from which it inherits methods and properties. An object can have its prototype set to another object, creating a prototype chain.
How do you create a deep clone of a complex object containing circular references?
You'd typically use a library like Lodash's cloneDeep
. A manual solution requires keeping a reference to cloned objects in a WeakMap
to handle circular references.
Explain the role of the Microtask Queue and Macrotask Queue in the Event Loop.
The Microtask Queue holds high-priority tasks like Promise callbacks and async/await code. The Macrotask Queue (or task queue) holds lower-priority tasks like setTimeout
and setInterval
.
Microtasks are processed before the next macrotask.
How would you write a function to implement Promise.race() from scratch?
You can return a new Promise((resolve, reject) => { ... })
. Inside, you would loop through the input promises and attach then
and catch
handlers that resolve or reject the main Promise as soon as the first element is ready.
What is the difference between Event Bubbling and Event Capturing?
Both describe the order in which elements receive events. Event bubbling starts at the inner element and propagates outwards to the parent elements.
Event capturing is the opposite, starting at the outermost element and propagating inwards.
Explain what a Memory Leak is and how to prevent them in JavaScript.
A Memory Leak occurs when objects or variables are no longer needed by an application but are still being referenced, preventing the garbage collector from freeing up that memory. They can be caused by uncleaned event listeners, forgotten timers, or global variables, amongst other potential threats.
Describe the internal workings of the new keyword.
The new
keyword is a special operator. When used before a JavaScript function call, it creates a new object with a prototype linked to the constructor's prototype, binds this
to the new object, executes the constructor, and returns the recently created object.
What are Service Workers and how do they improve web performance?
Service Workers are a type of web worker that runs in the background, separate from the main thread. They're a core part of building Progressive Web Apps (PWAs) and enable features like offline support and caching assets.
How do you implement currying?
Currying is a technique where a JavaScript function with multiple arguments is transformed into a series of functions, each accepting a single argument.
What is Functional Programming? How can you apply its principles in JavaScript?
Functional Programming is a programming paradigm that treats JavaScript functions as first-class citizens.
Key concepts include pure functions (functions that have no side effects when executed) and immutability.
The map
, filter
, and reduce
methods are great examples of this.
What is the purpose of WeakMap and WeakSet?
WeakMap
keys must be object types, while WeakSet
items must be object types. Both hold "weak" references to objects, meaning if there are no other references to an object, it can be garbage-collected, preventing memory leaks.
How would you optimize the rendering performance of a list with thousands of items?
You can use techniques like Virtualization (or windowing) to only render the visible elements of a list. This dramatically reduces the number of DOM elements and improves rendering performance.
How would you write a simple middleware function for an Express.js server?
A simple middleware function takes two arguments: req
and res
, and a third next
callback function. It performs some logic and then calls next()
to pass control to the next middleware in the stack.
How would you solve a problem with a large, deeply nested object where you need to access a property safely?
You can use optional chaining (?.
), which safely accesses nested properties without causing an error if an intermediate property is null
or undefined
.
Explain the observer pattern and how you would implement it.
The observer pattern is a software design pattern where an object (the "subject") maintains a list of dependents (the "observers") and notifies them of any state changes.
You can implement it using a simple subject class with subscribe
and notify
methods.
What are the most common data structures and algorithms in the context of JavaScript?
In JavaScript, common data structures include arrays, which are like ordered lists; objects, which store key-value pairs; and more complex ones like stacks, queues, linked lists, and trees.
The choice of a data structure is very important because it affects the efficiency of the code you write and how you solve problems in your program.
An algorithm is a set of well-defined, step-by-step instructions for solving a specific problem or performing a specific task (usually with your data structures).
In JavaScript coding, this can mean writing a function to sort an array, search for an item in a list, or traverse a tree. Interviewers ask about this to see how you think about problem-solving and efficiency. They want to know if you can write code that not only works but also performs well.
How does type coercion handle primitive values like an empty string?
Depending on the operation, the type coercion mechanism will handle the string in different ways.
For example, it will be treated as 0
in numerical operations (i.e, multiplications or divisions), and as a string if you’re using additions. Or even as false
in a Boolean context.
What are the key differences between Class syntax and Prototypal Inheritance?
The Class
syntax is just syntactic sugar over prototypal inheritance in JavaScript.
While Class
syntax gives the appearance of classical OOP inheritance, but the underlying mechanics still rely on prototypes. This simplifies the concept of prototypal inheritance for developers and opens the door for many new JavaScript devs to utilize the language with more familiar concepts instead of having to learn a completely new programming paradigm.
How do you handle authentication in a single-page application?
The most common and modern way to handle authentication in a Single Page Application (SPA) is with token-based authentication, most often using a JSON Web Token (JWT).
The process typically works like this:
When a user logs in, the SPA sends their credentials (username and password) to the backend.
The backend validates the credentials. If they are correct, it generates a JWT and sends it back to the client.
The SPA then stores this JWT in a secure location, usually in
localStorage
orsessionStorage
.For every subsequent request to a protected API endpoint, the SPA includes the JWT in the
Authorization
header of the HTTP request (instead of sending the credentials on every request).The backend, using middleware, intercepts the request and verifies the token's validity and signature. If the token is valid, the request is allowed to proceed. If it's invalid or missing, access is denied.
The great thing about this approach is that it’s stateless, meaning the server doesn't need to keep track of user sessions. It only needs to validate the token. This makes it highly scalable and ideal for the asynchronous nature of SPAs.
Explain the difference between Shallow and Deep copying of an object.
The main difference between shallow and deep copying of an object is that shallow
copying creates a new instance of an object, but copies references to nested objects. So changing the nested portions of the original object will affect both copies.
Deep
copying creates a new object and recursively copies all nested objects, so the original element and the copy are completely independent. This, in turn, means that any changes to the original object (no matter at what level) will not have a direct effect on the copy.