Cracking the JS interview doesn't have to be a nightmare. Here are the top JavaScript interview questions for freshers and experienced devs, explained simply with code.
Let’s be honest - JavaScript interviews are weird.
One minute you're talking about simple variables, and the next, you're deep in the weeds of the "Event Loop" or explaining why [] == ![] is somehow true. It’s enough to make even experienced developers sweat.
But here is the good news: most interviewers ask the same core questions. They just twist them a little.
If you can understand the logic behind the code rather than just memorizing answers, you will be fine. Whether you are a fresh graduate hoping to land your first role or an experienced dev brushing up on the basics, this guide is written for you.
I’ve broken this down into three sections: The Basics (don't skip these!), The Tricky Concepts (where most people fail), and Code Output Questions (the favorite weapon of interviewers).
Let's dive in.
Part 1: The Warm-Up (Beginner Friendly)
These are the questions designed to check if you actually know JavaScript or if you just memorised a framework like React.
1. What is the difference between var, let, and const?
(This is the #1 most asked question. Nail it.)
Back in the day, we only had var. It was messy. Now we have let and const.
var: Function-scoped. It can be re-declared and updated. It is "hoisted" (moved to the top) but initialised asundefined.let: Block-scoped (only exists within {}). Can be updated but not re-declared in the same block.const: Block-scoped. Cannot be updated or re-declared. It’s for constants.
The Human Tip: Tell the interviewer you default to using const. If you realize the value needs to change later, only then do you switch it to let. You rarely use var anymore.
2. What are the different data types in JavaScript?
JavaScript has primitive types (stored by value) and non-primitive types (stored by reference).
- Primitives: String, Number, Boolean, Undefined, Null, Symbol, BigInt.
- Non-Primitives: Objects (includes Arrays and Functions).
3. What is the DOM (Document Object Model)?
It is the tree structure representation of your HTML. JavaScript uses it to interact with and modify the page.
4. What is the "Virtual DOM" (Concept)?
Used by libraries like React. It’s a lightweight copy of the real DOM in memory. When state changes, JS compares the Virtual DOM to the previous version (Diffing) and only updates the parts of the Real DOM that actually changed.
5. null vs undefined: What’s the difference?
- Undefined: The variable exists, but you haven't given it a value yet. JavaScript does this automatically.
- Null: You intentionally set the value to "nothing" or "empty." It is a developer's choice.
6. What is NaN?
It stands for "Not a Number." Ironically, its type is actually 'number'. You get this when you try to do math with something that isn't a number (e.g., 5 * "apple").
7. What is strict mode ('use strict')?
It's a way to opt-in to a stricter version of JavaScript. It prevents you from using undeclared variables and throws errors for bad practices that JS usually ignores.
- Usage: Add
"use strict"; at the top of your file.
8. What is the difference between specific "undeclared" and "undefined" variables?
- Undefined: Declared but no value (
let a;). - Undeclared: You never created it (no
var/let/const), but tried to use it. This throws aReferenceError.
9. What is "Hoisting"?
Hoisting sounds fancy, but it just means JavaScript moves your variable and function declarations to the top of their scope before the code runs.
- With
var: You can use the variable before declaring it, but it will beundefined. - With
letandconst: They are technically hoisted, but they stay in a "Temporal Dead Zone" (scary name, right?). Basically, you can't touch them until the line of code where they are declared.
Example:
console.log(myVar); // Output: undefined
var myVar = 5;
console.log(myLet); // Output: ReferenceError!
let myLet = 10;
10. == vs ===: Which one should you use?
Always use === (Strict Equality).
==(Loose Equality): Checks value but ignores type. It tries to be helpful by converting types for you (Type Coercion).5 == "5"is True. (Scary!)
===(Strict Equality): Checks both value and type.5 === "5"is False. (Safe!)
11. What are "falsy" values in JavaScript?
These are values that evaluate to false when checking a condition. There are only 6 main ones you need to remember:
false0(zero)""(empty string)nullundefinedNaN(Not a Number)
Everything else is "truthy"—even empty arrays [] and empty objects {}!
12. What are Arrow Functions?
Introduced in ES6, arrow functions provide a shorter way to write functions. Instead of:
function add(a, b) {
return a + b;
}
You can write:
const add = (a, b) => a + b;
Beyond being shorter, arrow functions do not have their own this or arguments object. They are great for simple tasks, but shouldn't be used as methods inside objects if you need to use this.
13. LocalStorage vs SessionStorage vs Cookies.
- LocalStorage: Stores data with no expiration time. (5-10MB).
- SessionStorage: Stores data only while the tab is open. Cleared on close.
- Cookies: Small data (4KB) sent to the server with every request. Used for auth.
14. What is Event Delegation?
Instead of adding an event listener to every single button, you add one listener to the parent div. You check event.target to see which child was clicked. This saves memory.
15. Is JavaScript statically typed or dynamically typed?
It is dynamically typed. You don't have to define types (like int or string) when creating variables. A variable can hold a number today and a string tomorrow.
16. What is Type Coercion?
It's when JavaScript secretly converts one data type into another.
- Example:
1 + "2"becomes"12"(Number converted to String). - Example:
if (1)works because1is coerced totrue.
17. What are Template Literals?
Introduced in ES6, they allow you to embed variables in strings using backticks (`) and ${} syntax.
- Example: `Hello, ${name}!` instead of 'Hello, ' + name + '!'.
Part 2: The "Make or Break" Concepts (Intermediate)
This is where the interview gets real. If you can explain these simply, you’re hired.
18. Explain "Closures" like I’m 5.
A closure is simply a function that remembers the variables from the place where it was created, even after that place is gone.
Imagine a backpack. You (the function) go to school (execute). When you leave home (the outer function), you take your backpack with you. Even though you are no longer home, you still have access to the snacks (variables) inside your backpack.
Code Example:
function outer() {
let count = 0; // This variable is "remembered"
return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // Output: 1
counter(); // Output: 2
Why it matters: This is how we create private variables in JavaScript.
19. What is the "Event Loop"?
JavaScript is single-threaded. This means it can only do one thing at a time. So, how does it handle huge tasks (like fetching data from a server) without freezing your screen?
It uses the Event Loop.
- Call Stack: Runs simple code immediately (like
console.log). - Web APIs: If you use
setTimeoutorfetch, JS hands that task off to the browser (Web API) and moves on. - Callback Queue: Once the big task is done, it waits in a line (queue).
- The Event Loop: This is the bouncer. It keeps checking the Call Stack. Only when the stack is empty does it let the tasks from the Queue enter.
20. Explain Promises.
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. It has three states: Pending, Fulfilled (Resolved), or Rejected.
21. What is "Callback Hell"?
When you nest multiple callbacks inside each other (pyramid of doom), making code unreadable.
- Solution: Use Promises or Async/Await.
22. Difference between Promise.all and Promise.allSettled.
Promise.all: Fails immediately if any promise rejects. (All or nothing).Promise.allSettled: Waits for all promises to finish, regardless of whether they succeeded or failed.
23. Promises vs. Async/Await
They effectively do the same thing (handle async operations), but async/await looks cleaner.
- Promise: Uses
.then()chains. It can get messy if you have too many steps (Callback Hell). - Async/Await: syntactic sugar built on top of Promises. It makes async code look like synchronous code.
Interviewer asks: "Can you use await without async?" Answer: Generally no, await must be inside an async function (though modern modules now allow top-level await).
24. What is this keyword?
The most hated keyword in JS. The value of this depends on how the function is called.
- Global context:
thisrefers to the window object. - Object method:
thisrefers to the object calling the method. - Arrow function:
thisdoesn't care who called it; it stealsthisfrom the surrounding code (lexical scope).
The Trap:
const obj = {
name: "JS",
regularFunc: function() { console.log(this.name) }, // Works ('JS')
arrowFunc: () => { console.log(this.name) } // Fails (undefined)
};
Tip: Never use arrow functions as object methods if you need this.
25. What is an IIFE (Immediately Invoked Function Expression)?
A function that runs as soon as it is defined. It’s mostly used to create a private scope so variables don't leak into the global window.
(function() {
console.log("I run immediately!");
})();
26. What is the difference between Function Declaration and Function Expression?
- Declaration:
function abc() {}(Hoisted, can use before definition). - Expression:
const abc = function() {}(Not hoisted, behaves like a variable).
27. What is a Higher-Order Function?
A function that does one of two things:
- Takes another function as an argument (like
map, filter). - Returns a function.
28. What is the "arguments" object?
An array-like object available inside standard functions (not arrow functions) that contains all the values passed to that function, even if you didn't define parameters.
29. Explain Arrow Functions vs Regular Functions.
- Syntax: Arrow functions are shorter
() => {}. - Arguments: Arrow functions don't have the
argumentsobject. this: Arrow functions do not have their ownthis; they inherit it from the parent scope. Regular functions definethisbased on how they are called.
30. What is a Callback Function?
A function passed into another function to be executed later.
- Example:
setTimeout(callback, 1000)orbutton.addEventListener('click', callback).
31. What are Default Parameters?
You can set a default value for a function parameter if the user doesn't provide one.
function greet(name = "Guest") {
return `Hi ${name}`;
}
32. Microtasks vs Macrotasks.
- Microtasks: High priority (Promises,
queueMicrotask). These run immediately after the current script, before rendering. - Macrotasks: Low priority (
setTimeout,setInterval). These run in the next loop cycle.
33. What is the Fetch API?
The modern, built-in way to make network requests (AJAX) in browsers. It uses Promises. fetch('url').then(res => res.json()).then(data => console.log(data));
34. How do you handle errors in Async/Await?
You use a try...catch block.
try {
const data = await fetch(url);
} catch (error) {
console.log("Something went wrong");
}
35. What is a Generator Function?
A function that can be paused and resumed. It uses the function* syntax and the yield keyword.
36. What is a Race Condition?
When the output depends on the sequence or timing of uncontrollable events (like network requests returning in a random order).
37. What is Currying?
Transforming a function like f(a, b, c) into f(a)(b)(c). It breaks a function with multiple arguments into a chain of functions each taking one argument.
38. What is the difference between map() and forEach()?
map(): Returns a new array. Use this when you want to transform data.forEach(): Returnsundefined. It just loops through. Use this for side effects (like saving to a database).
39. What are call, apply, and bind?
They are methods to manually set what this refers to.
call: Invokes function immediately, arguments listed individually.apply: Invokes function immediately, arguments passed as an array.bind: Returns a new function with this permanently set (does not run immediately).
40. What is Prototypal Inheritance?
JavaScript objects have a hidden link to another object called a "prototype." If you ask for a property that the object doesn't have, JS looks up the chain to the prototype to find it.
41. What is the difference between Shallow Copy and Deep Copy?
- Shallow Copy: Copies the object, but nested objects are still linked to the original (references). Changing nested data affects both.
- Deep Copy: Creates a completely independent clone. (JSON.parse(JSON.stringify()) is a common hack).
42. What is Destructuring?
Unpacking values from arrays or properties from objects into distinct variables.
const { name, age } = userObject;
const [ first, second ] = numberArray;
43. What is the Spread Operator (...)?
It expands an array or object into individual elements. Great for combining arrays or cloning objects.
const newArr = [...oldArr, 4, 5];
44. Set vs Array: What’s the difference?
- Array: Can hold duplicate values. Ordered list.
- Set: Can only hold unique values. Order is insertion-based.
45. Map vs Object: When to use which?
- Object: Keys must be strings or symbols. Not optimized for frequent additions/removals.
- Map: Keys can be anything (even other objects). Remembers insertion order. Better performance for large data sets.
46. What is slice vs splice?
slice: Does not modify the original array. Returns a piece of it (like cutting a slice of cake).splice: Modifies the original array. Can remove items or add items (like splicing a wire).
47. Event Bubbling vs Event Capturing.
- Bubbling (Default): The event starts at the target element and bubbles up to the root (parents).
- Capturing: The event goes down from the root to the target.
48. stopImmediatePropagation vs stopPropagation.
stopPropagation: Stops the event from bubbling up to parents.stopImmediatePropagation: Stops bubbling AND prevents other listeners on the same element from running.
49. defer vs async in script tags.
async: Downloads script in parallel, runs it as soon as it downloads (might block HTML parsing).defer: Downloads in parallel, but waits until HTML is fully parsed to run. (Better for performance).
50. What is Memoization?
An optimization technique. You cache the result of a heavy function call so that if you call it again with the same arguments, it returns the cached result instantly.
51. Debounce vs Throttle.
- Debounce: "Wait until the user stops." (e.g., Search bar suggestion).
- Throttle: "Run at most once every X seconds." (e.g., Scrolling updates).
52. What is a Polyfill?
Code that provides functionality on older browsers that do not natively support it. It "fills in" the gaps.
Part 3: Tricky Output Questions (The "Gotchas")
Interviewers love these because they test if you understand how JS works under the hood.
53. The setTimeout Trick
console.log("A");
setTimeout(() => console.log("B"), 0);
console.log("C");
Output: A -> C -> B
Why? Even though the timer is 0ms, setTimeout goes to the Web API and then the Callback Queue. The Event Loop won't let "B" run until the main stack (A and C) is finished.
54. Array Equality
console.log([] == []);
console.log([1] === [1]);
Output: false, false
Why? In JavaScript, arrays are Objects (Reference types). You are comparing memory references, not values. Since they are two different arrays in memory, they are not equal.
55. String Coercion
console.log(1 + "1");
console.log(1 - "1");
Output: "11", 0
Why?
+triggers concatenation if one side is a string. So 1 becomes "1".-only works on numbers. So JS converts "1" to a number.
56. The Scope Trap
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
Output: 3 3 3 (printed three times)
Why? var is function-scoped, not block-scoped. By the time the setTimeout runs (after 100ms), the loop has already finished, and i has become 3. Fix: Change var to let. let creates a new i for every loop iteration.
Part 4: Coding Challenges (Live Coding)
In many rounds, you will have to write code on a whiteboard or Notepad. Here are two classics.
57. How do you check if a string is a palindrome?
(A word that reads the same backward, e.g., "racecar")
Simple Solution:
function isPalindrome(str) {
// 1. Split into array, 2. Reverse array, 3. Join back to string
let reversed = str.split('').reverse().join('');
return str === reversed;
}
Pro Tip: Ask the interviewer if you need to handle spaces or capital letters. If yes, use .toLowerCase() first.
58. How do you remove duplicates from an array?
The Old Way (Loop):
let arr = [1, 2, 2, 3];
let unique = [];
arr.forEach(element => {
if (!unique.includes(element)) {
unique.push(element);
}
});
The Modern Way (One Liner):
let unique = [...new Set(arr)];
Explanation: A Set is a data structure that only allows unique values. We convert the array to a Set, and then spread it ... back into an array.
59. What will be the output of 0.1 + 0.2 === 0.3?
The answer is false. This is because of how computers handle floating-point numbers. The actual result of 0.1 + 0.2 is 0.30000000000000004. This is a classic question to see if you understand the limits of the Number type.
Tips for a Successful JavaScript Interview
Knowing the answers is only half the battle. How you present them matters as much.
- Don't Rush: If you get a coding question, take a minute to think. Explain your logic out loud before you start typing.
- Ask Questions: If a prompt is vague, ask for clarification. Does the array contain only numbers? Should I worry about empty strings?
- Use Modern Syntax: Using
let,const, and arrow functions shows that you are up-to-date with the industry standards. - Admit What You Don't Know: If you are stuck, don't fake it. Say, "I haven't used that specific feature much, but based on what I know about X, I think it works like Y."
- Focus on the "Why": Don't just give the definition. Give a real-world example of where you would use that concept in a project.
Conclusion
JavaScript interviews can feel intimidating because the language has so many quirks. But remember: Communication is more important than syntax.
If you get stuck on a question, don't freeze. Say, "I'm not 100% sure, but here is my logic..." or "I know this involves the Event Loop, let me try to work it out." Interviewers love hearing your thought process.
Review these questions, practice writing the code snippets by hand, and walk into that interview room with confidence. You’ve got this!
Frequently Asked Questions (FAQ)
Q: Do I need to know Algorithms and Data Structures (DSA) for a JavaScript interview?
A: It depends. For big tech companies (FAANG), yes. For smaller startups or frontend roles, they care more about practical JS skills (DOM manipulation, API fetching, Async logic) than complex sorting algorithms.
Q: Should I learn React/Vue/Angular before the interview?
A: Know the basics of one framework, but Master Vanilla JavaScript first. A developer who knows React but can't explain this or closures is a red flag for hiring managers.
Q: How long should my answers be?
A: Keep them short and sweet. Define the concept, give a real-world analogy, and provide a code example. If they want more depth, they will ask.
That’s a wrap!
Thank you for taking the time to read this article! I hope you found it informative and enjoyable. If you did, please consider sharing it with your friends and followers. Your support helps me continue creating content like this.
Stay updated with our latest content by signing up for our email newsletter! Be the first to know about new articles and exciting updates directly in your inbox. Don't miss out—subscribe today!
If you'd like to support my work directly, you can buy me a coffee . Your generosity is greatly appreciated and helps me keep bringing you high-quality articles.
Thanks!
Faraz 😊

.jpg)