Top 50 JavaScript Interview Questions and Coding Challenges
Quick Answer: This guide covers 30 important JavaScript interview questions and 20 coding challenges. It starts with core concepts and moves towards asynchronous programming, browser APIs and problem-solving. Each answer uses simple explanations and practical examples.
Use this guide to prepare for JavaScript developer interviews. Practise the coding challenges without looking at the solutions first.
1. How to Prepare for JavaScript Interviews
JavaScript interviews test more than syntax. Interviewers want to understand your thinking and coding approach.
- Fundamentals: Variables, data types, scope and operators.
- Functions: Closures, callbacks, arrow functions and higher-order functions.
- Objects: Prototypes, inheritance, destructuring and references.
- Asynchronous JavaScript: Promises, async/await and the event loop.
- Browser development: DOM, events, storage and event delegation.
- Coding: Arrays, strings, objects and common algorithms.
Interview tip: Explain your approach before writing code. Discuss edge cases and time complexity. Then test your solution with sample inputs.
2. JavaScript Execution: How the Main Parts Work Together
JavaScript uses different features to process application data. Consider a shopping application displaying an order summary.
Animation 1: JavaScript application execution flow
The highlighted stages show how an application handles input, calculations, asynchronous work and screen updates.
The animation uses separate stages for this article. Each stage has readable text and independent spacing. It does not move or scale text during animation.
3. Core JavaScript Interview Questions (1–10)
1. What is JavaScript?
JavaScript is a programming language used to build interactive applications. It runs in browsers and other environments, including Node.js.
Developers use it for websites, APIs, backend services and mobile applications.
2. What are the different data types in JavaScript?
JavaScript has seven primitive data types and one non-primitive category.
string– text values.number– integer and decimal numbers.bigint– very large integers.boolean– true or false.undefined– a variable without an assigned value.null– an intentional absence of value.symbol– a unique symbol value.object– collections, arrays and other objects.
3. What is the difference between var, let and const?
var is function-scoped and can be redeclared. let is block-scoped and can be reassigned. const is block-scoped and cannot be reassigned.
Prefer const by default. Use let when reassignment is needed.
4. What is the difference between == and ===?
== compares values after possible type conversion. === compares values without type conversion.
Example: 5 == "5" returns true. 5 === "5" returns false.
5. What is type coercion?
Type coercion means JavaScript converts a value from one type to another. Some conversions happen automatically.
Example: "5" + 2 produces "52". But "5" - 2 produces 3.
6. What is the difference between null and undefined?
undefined usually means a value has not been assigned. null represents an intentional empty value.
Example: a missing optional customer address may be represented by null.
7. What is NaN in JavaScript?
NaN means Not-a-Number. It represents an invalid numeric result.
Use Number.isNaN(value) to check whether a value is NaN.
8. What is the difference between primitive and reference types?
Primitive values are copied as values. Objects and arrays are copied as references.
Changing an object through one reference can affect another reference to it.
9. What is truthy and falsy in JavaScript?
Truthy values behave like true in conditions. Falsy values behave like false.
Falsy values include false, 0, -0, 0n, empty string, null, undefined and NaN. Empty arrays and empty objects are truthy.
10. What is the difference between function declaration and function expression?
A function declaration defines a named function directly. A function expression stores a function inside a variable.
Function declarations are hoisted with their function body. Function expressions follow the initialization rules of their variable.
4. Functions, Scope and Objects (11–20)
11. What is hoisting in JavaScript?
Hoisting describes how declarations are processed before code execution. Function declarations can be called before their position in the source.
var declarations are initialized with undefined. let and const remain unavailable before initialization.
12. What is scope in JavaScript?
Scope decides where a variable can be accessed. JavaScript supports global, function and block scope.
Variables declared with let and const follow block scope.
13. What is a closure?
A closure happens when a function remembers variables from its outer scope. The outer function can finish running, but those variables remain accessible.
Closures help create private state and reusable function factories.
14. What is a callback function?
A callback is a function passed to another function. The receiving function calls it when needed.
Callbacks are common in event handling, array methods and asynchronous operations.
15. What is an arrow function?
An arrow function provides a shorter function syntax. It does not create its own this value.
It also does not have its own arguments object. Arrow functions cannot be used as constructors.
16. What is the difference between call, apply and bind?
All three methods control the this value for a function.
call()invokes the function with separate arguments.apply()invokes it with arguments in an array-like value.bind()returns a new function with a chosen this value.
17. What is a higher-order function?
A higher-order function accepts another function or returns a function. Array methods such as map, filter and reduce are common examples.
18. What is the difference between map() and forEach()?
map() creates and returns a new array. forEach() runs a callback for each item and returns undefined.
Use map when you need transformed results. Use forEach for actions such as logging or updating another value.
19. What is destructuring?
Destructuring extracts values from arrays or properties from objects. It makes assignments shorter and easier to read.
20. What is the difference between spread and rest operators?
Both use three dots. Spread expands values from an iterable or object. Rest collects remaining values into an array or object.
Their purpose depends on where you use them.
5. Asynchronous JavaScript and Browser Concepts (21–30)
21. What is a Promise?
A Promise represents the future result of an asynchronous operation. It can be pending, fulfilled or rejected.
Use then() for success and catch() for errors.
22. What is async/await?
async makes a function return a Promise. await waits for a Promise inside an async function.
It makes asynchronous code easier to read. Use try/catch to handle rejected Promises.
23. What is the event loop?
The event loop coordinates JavaScript execution and queued callbacks. It allows asynchronous work without blocking the main call stack.
Promise callbacks use the microtask queue. Timer callbacks use the task queue.
24. What is the difference between microtasks and macrotasks?
Microtasks include Promise callbacks and queueMicrotask callbacks. Tasks include setTimeout and many browser event callbacks.
After the current stack finishes, the runtime processes microtasks before moving to the next task.
25. What is Promise.all()?
Promise.all() waits for every supplied Promise to fulfill. It rejects when one supplied Promise rejects.
It is useful when several independent requests must all succeed.
26. What is the difference between Promise.all() and Promise.allSettled()?
Promise.all() rejects when one Promise rejects. Promise.allSettled() waits for every Promise to settle.
Use allSettled when you need every result, including failures.
27. What is the DOM?
DOM means Document Object Model. It represents an HTML page as a tree of objects.
JavaScript can read and change these objects. This allows a page to respond to user actions.
28. What is event bubbling?
Event bubbling means an event moves from the target element towards its ancestors. A parent can handle events raised by its children.
29. What is event delegation?
Event delegation attaches one event listener to a common parent. The parent handles events from matching child elements.
It reduces the need for many individual listeners. It is useful for dynamic lists.
30. What is the difference between localStorage, sessionStorage and cookies?
localStorage stores data until it is removed. sessionStorage stores data for a browser tab session. Cookies can be sent with matching HTTP requests.
Cookies support server-side session patterns and security attributes. Do not store sensitive data in browser storage without proper security design.
6. Animation: How the JavaScript Event Loop Works
Consider a shopping page that loads order information. Synchronous code runs first. Promise callbacks run before timer callbacks after the current stack finishes.
Animation 2: Event loop execution sequence
The stages highlight the path from current execution to queued callbacks. The browser and JavaScript runtime provide the surrounding scheduling mechanisms.
Try this example. Predict the output before reading it.
Example 1: Promise and setTimeout execution order
console.log("Start");
setTimeout(() => {
console.log("Timer");
}, 0);
Promise.resolve().then(() => {
console.log("Promise");
});
console.log("End");
Expected output
Start End Promise Timer
The current stack completes before queued callbacks run. Promise reactions run before the timer task in this example.
7. Twenty JavaScript Coding Challenges (31–50)
These challenges cover common interview patterns. Try each problem before checking its solution.
Challenge 31: Reverse a String
Return the given string in reverse order.
Solution
function reverseString(value) {
return value.split("").reverse().join("");
}
console.log(reverseString("javascript"));
tpircsavaj
Challenge 32: Check Whether a String Is a Palindrome
A palindrome reads the same in both directions. Ignore letter case in this example.
function isPalindrome(value) {
const cleaned = value.toLowerCase();
return cleaned === cleaned.split("").reverse().join("");
}
console.log(isPalindrome("Madam"));
true
Challenge 33: Find the Largest Number in an Array
function findLargest(numbers) {
if (numbers.length === 0) return undefined;
return numbers.reduce((largest, current) =>
current > largest ? current : largest
);
}
console.log(findLargest([12, 45, 7, 89, 23]));
89
Challenge 34: Find the Second Largest Distinct Number
function secondLargest(numbers) {
const unique = [...new Set(numbers)].sort((a, b) => b - a);
return unique.length > 1 ? unique[1] : undefined;
}
console.log(secondLargest([10, 5, 20, 20, 8]));
10
Challenge 35: Remove Duplicate Values from an Array
function removeDuplicates(items) {
return [...new Set(items)];
}
console.log(removeDuplicates([1, 2, 2, 3, 1]));
[1, 2, 3]
Challenge 36: Count Character Frequency
function countCharacters(value) {
const counts = {};
for (const character of value) {
counts[character] = (counts[character] || 0) + 1;
}
return counts;
}
console.log(countCharacters("hello"));
{ h: 1, e: 1, l: 2, o: 1 }
Challenge 37: Find the First Non-Repeating Character
function firstUnique(value) {
for (const character of value) {
if (value.indexOf(character) === value.lastIndexOf(character)) {
return character;
}
}
return undefined;
}
console.log(firstUnique("swiss"));
w
Challenge 38: Find Missing Number from 1 to N
Assume the array contains distinct values from 1 to N, with one missing.
function findMissing(numbers, n) {
const expected = n * (n + 1) / 2;
const actual = numbers.reduce((sum, value) => sum + value, 0);
return expected - actual;
}
console.log(findMissing([1, 2, 4, 5], 5));
3
Challenge 39: Find Two Numbers That Add to a Target
function twoSum(numbers, target) {
const seen = new Map();
for (let i = 0; i < numbers.length; i++) {
const needed = target - numbers[i];
if (seen.has(needed)) return [seen.get(needed), i];
seen.set(numbers[i], i);
}
return [];
}
console.log(twoSum([2, 7, 11, 15], 9));
[0, 1]
Challenge 40: Move All Zeroes to the End
function moveZeroes(numbers) {
let position = 0;
for (const number of numbers) {
if (number !== 0) numbers[position++] = number;
}
while (position < numbers.length) {
numbers[position++] = 0;
}
return numbers;
}
console.log(moveZeroes([0, 1, 0, 3, 12]));
[1, 3, 12, 0, 0]
Challenge 41: Check Whether Two Strings Are Anagrams
Two strings are anagrams when they contain the same letters with matching counts.
function areAnagrams(first, second) {
const normalize = value =>
value.toLowerCase().split("").sort().join("");
return normalize(first) === normalize(second);
}
console.log(areAnagrams("listen", "silent"));
true
Challenge 42: Flatten a Nested Array
function flattenArray(items) {
return items.flat(Infinity);
}
console.log(flattenArray([1, [2, [3, 4]]]));
[1, 2, 3, 4]
Challenge 43: Find Common Values in Two Arrays
function findCommon(first, second) {
const secondSet = new Set(second);
return [...new Set(first)].filter(value => secondSet.has(value));
}
console.log(findCommon([1, 2, 3], [2, 3, 4]));
[2, 3]
Challenge 44: Find the Factorial of a Number
function factorial(number) {
if (number < 0) return undefined;
let result = 1;
for (let i = 2; i <= number; i++) {
result *= i;
}
return result;
}
console.log(factorial(5));
120
Challenge 45: Generate the Fibonacci Sequence
function fibonacci(count) {
const result = [];
let first = 0;
let second = 1;
for (let i = 0; i < count; i++) {
result.push(first);
[first, second] = [second, first + second];
}
return result;
}
console.log(fibonacci(7));
[0, 1, 1, 2, 3, 5, 8]
Challenge 46: Capitalize the First Letter of Each Word
function capitalizeWords(value) {
return value.replace(/\b\w/g, character => character.toUpperCase());
}
console.log(capitalizeWords("javascript interview questions"));
Javascript Interview Questions
Challenge 47: Find the Difference Between Two Arrays
function arrayDifference(first, second) {
const secondSet = new Set(second);
return first.filter(value => !secondSet.has(value));
}
console.log(arrayDifference([1, 2, 3], [2, 4]));
[1, 3]
Challenge 48: Group Objects by a Property
function groupByRole(employees) {
return employees.reduce((groups, employee) => {
const role = employee.role;
groups[role] = groups[role] || [];
groups[role].push(employee.name);
return groups;
}, {});
}
const employees = [
{ name: "Ravi", role: "Developer" },
{ name: "Priya", role: "Tester" },
{ name: "Arjun", role: "Developer" }
];
console.log(groupByRole(employees));
{
Developer: ["Ravi", "Arjun"],
Tester: ["Priya"]
}
Challenge 49: Implement a Debounce Function
Debouncing delays a function until calls stop for a chosen time. It is useful for search input handling.
function debounce(callback, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => callback(...args), delay);
};
}
const search = debounce(value => {
console.log("Search:", value);
}, 300);
search("JavaScript");
Search: JavaScript
Challenge 50: Implement a Throttle Function
Throttling limits how often a function can run. It is useful for scroll and resize events.
function throttle(callback, delay) {
let lastRun = 0;
return (...args) => {
const now = Date.now();
if (now - lastRun >= delay) {
lastRun = now;
callback(...args);
}
};
}
const handleScroll = throttle(() => {
console.log("Scroll handled");
}, 500);
Example usage
window.addEventListener("scroll", handleScroll);
Expected behaviour
The callback runs at most once per 500 milliseconds.
8. Animation: From User Input to a Browser Update
JavaScript often connects browser events with application logic. Event delegation can help manage dynamic product lists.
Animation 3: Browser event handling flow
This animation shows one complete browser interaction. The four stages highlight in sequence and repeat automatically.
9. Important Coding Patterns to Practise
| Pattern | Useful for | Example challenge |
|---|---|---|
| Two pointers | Working from two positions | Palindrome check |
| Hash map | Fast value lookup | Two Sum |
| Set | Unique values | Remove duplicates |
| Sliding window | Contiguous ranges | Longest substring |
| Frequency counter | Counting repeated values | Character frequency |
| Recursion | Breaking problems into smaller calls | Nested array flattening |
| Sorting | Ordering values | Second largest number |
| Closures | Keeping private state | Debounce and throttle |
10. Common Mistakes in JavaScript Interviews
1. Using == without understanding conversion
Prefer strict equality for predictable comparisons. Use loose equality only when its conversion rules are intentional.
2. Forgetting edge cases
Test empty arrays, duplicate values, negative numbers and missing inputs. Confirm what your function should return for each case.
3. Mutating input unexpectedly
Methods such as sort and reverse change the original array. Make a copy when the original value must remain unchanged.
4. Ignoring asynchronous errors
Handle rejected Promises with catch or try/catch. Do not leave failed requests unhandled.
5. Writing code without explaining it
Explain your approach and trade-offs. Mention time and space complexity where useful.
11. Interview Preparation Roadmap
Animation 4: Your JavaScript preparation journey
The roadmap highlights a practical learning order. Complete each stage before moving to harder problems.
Suggested seven-day practice plan
| Day | Topics | Practice |
|---|---|---|
| Day 1 | Variables, types and operators | Questions 1–10 |
| Day 2 | Functions, scope and closures | Questions 11–17 |
| Day 3 | Objects and array methods | Questions 18–20, 33–38 |
| Day 4 | Promises and event loop | Questions 21–26 |
| Day 5 | DOM and browser events | Questions 27–30 |
| Day 6 | String and array problems | Challenges 31–48 |
| Day 7 | Advanced coding patterns | Challenges 49–50 and revision |
12. Frequently Asked JavaScript Interview Questions
Which JavaScript topics should beginners learn first?
Start with variables, data types, operators, conditions and loops. Then learn functions, arrays, objects and basic DOM operations.
Are JavaScript coding challenges important?
Yes. Coding challenges test your problem-solving and language knowledge. Practise explaining your solution while writing it.
What is the best way to practise JavaScript?
Write code without copying solutions. Test normal inputs and edge cases. Review your solution for clarity and performance.
Should I learn JavaScript before React?
Yes. Learn functions, arrays, objects, modules, promises and DOM basics first. These concepts make React easier to understand.
13. Next Steps and Community
- Try It Yourself: Solve all 20 coding challenges without looking at the solutions.
- Explain Your Answers: Practise speaking each concept in simple words.
- Improve Your Code: Compare different solutions and discuss their complexity.
- Build Projects: Apply JavaScript concepts in real applications.
- Share Your Knowledge: Share your solutions and help other learners.
Final takeaway: Strong JavaScript skills come from clear concepts and regular practice. Understand the behaviour, write the code and test edge cases. Keep learning and build something useful every day.
Upgradix by Shrash Studio
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.