JavaScript Interview
Questions & Answers
🌱 Beginner Questions Q1–Q10
JavaScript is a lightweight, interpreted, high-level programming language primarily used to make web pages interactive. It runs directly in the browser without needing to be compiled first.
Originally created for the browser, JavaScript now also runs on the server (via Node.js), in mobile apps, and even in embedded systems. It is one of the three core technologies of the web alongside HTML and CSS.
- HTML — defines the structure of a page
- CSS — controls the styling and layout
- JavaScript — adds behaviour and interactivity
var, let, and const?This is one of the most asked JavaScript questions. The three keywords differ in scope, hoisting behaviour, and reassignment rules.
In modern JavaScript, prefer const by default. Use let only when you need to reassign the variable. Avoid var in new code.
let/const to impress the interviewer.== and === in JavaScript?== is the loose equality operator — it compares values after performing type coercion. === is the strict equality operator — it compares both value AND type without any coercion.
Always prefer === in real code to avoid unexpected bugs caused by implicit type coercion.
JavaScript has 8 data types, divided into two categories:
Primitive types (7): stored by value
String— text:"hello"Number— integers and floats:42,3.14BigInt— very large integers:9007199254740991nBoolean—trueorfalseundefined— declared but not assignednull— intentional absence of valueSymbol— unique identifier (ES6+)
Non-primitive (1): stored by reference
Object— includes arrays, functions, dates, etc.
typeof null returns "object" — this is a well-known JavaScript bug that has never been fixed for backwards compatibility reasons. Mentioning this shows depth.Hoisting is JavaScript's default behaviour of moving variable and function declarations to the top of their scope during the compilation phase — before the code runs.
Only declarations are hoisted — not initialisations. Function declarations are fully hoisted; function expressions are not.
null and undefined?Both represent the absence of a value but they are used differently and have different types:
undefined— a variable has been declared but has not been assigned a value yet. JavaScript sets this automatically.null— an intentional assignment meaning "no value". A developer explicitly sets this to indicate an empty or unknown value.
Arrow functions (introduced in ES6) are a shorter syntax for writing functions. But they have an important behavioural difference: they do not have their own this binding.
- Arrow functions cannot be used as constructors (no
new) - Arrow functions have no
argumentsobject - Best used for callbacks and non-method functions
Template literals (ES6) are string literals that allow embedded expressions and multi-line strings using backticks (` `) instead of quotes.
forEach and map?Both iterate over arrays, but the key difference is what they return:
forEach— executes a function on each element. Returnsundefined. Used for side effects.map— creates and returns a new array of transformed values. Does not mutate the original.
Use map when you need the transformed values. Use forEach when you just need to run something for each item (logging, DOM updates, etc.).
Destructuring is an ES6 syntax that lets you unpack values from arrays or properties from objects into separate variables in a single line.
⚡ Intermediate Questions Q11–Q22
A closure is a function that retains access to its outer (enclosing) scope even after the outer function has finished executing. The inner function "closes over" the variables of the outer function.
Closures are fundamental to many JavaScript patterns including module patterns, private variables, currying, and React hooks. They are one of the most important concepts to understand deeply.
JavaScript is single-threaded — it can only do one thing at a time. The Event Loop is the mechanism that allows JavaScript to handle asynchronous operations (like timers, network requests) without blocking the main thread.
- Call Stack — where synchronous code executes, one frame at a time.
- Web APIs — browser-provided features (setTimeout, fetch, DOM events) that run outside the call stack.
- Callback Queue (Task Queue) — completed async callbacks waiting to run.
- Microtask Queue — higher-priority queue for Promises and
queueMicrotask. - Event Loop — constantly checks if the call stack is empty. If it is, it moves tasks from the queues into the stack.
A Promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states: pending, fulfilled, or rejected.
Promises replaced callback-based async patterns and enabled the cleaner async/await syntax built on top of them.
async/await and how does it work?async/await is syntactic sugar over Promises that makes asynchronous code look and behave more like synchronous code. An async function always returns a Promise. await pauses execution inside that function until the Promise resolves.
await only pauses the async function — not the whole program. The event loop continues running other code while waiting.Event delegation is a technique where instead of attaching event listeners to each individual child element, you attach a single listener to a parent element and let events bubble up to it.
Benefits: fewer event listeners = better memory usage; works on dynamically added elements; cleaner code.
Both use the ... syntax but serve opposite purposes:
this in JavaScript and how does its value get determined?The value of this depends on how a function is called, not where it is defined. This makes it one of the trickiest parts of JavaScript.
- Global context:
this=window(browser) orglobal(Node.js) - Object method:
this= the object that owns the method - Arrow function:
this= inherited from the enclosing lexical scope call/apply/bind:this= explicitly set value- Class / constructor:
this= the new instance
call, apply, and bind?All three methods explicitly set the this value for a function, but they differ in how and when the function executes:
A shallow copy copies only the top-level properties. Nested objects still reference the same memory. A deep copy creates a completely independent copy of every level.
Other deep copy methods: JSON.parse(JSON.stringify(obj)) (has limitations with functions/dates), or libraries like Lodash's _.cloneDeep.
Both are techniques to control how often a function executes in response to rapid events (like typing or scrolling):
- Debounce — waits until the user stops triggering the event for a set time, then fires once. Best for search inputs, form validation.
- Throttle — fires at most once per set interval, no matter how often the event triggers. Best for scroll events, resize handlers.
import / export)?ES6 modules allow you to split code into separate files and share functionality between them using export and import.
Memoization is an optimisation technique that caches the results of function calls so that the same computation isn't repeated if the same arguments are passed again.
🔥 Advanced Questions Q23–Q30
In JavaScript, every object has an internal link to another object called its prototype. When you access a property that doesn't exist on an object, JavaScript looks up the prototype chain until it finds it or reaches null.
ES6 class syntax is built on top of prototypal inheritance — it's syntactic sugar that doesn't change the underlying prototype-based model.
Generators are special functions that can be paused and resumed. They use function* syntax and the yield keyword to pause execution and return a value, then resume from where they left off.
Generators are useful for lazy evaluation, infinite sequences, and were the foundation for async/await before it was natively supported.
WeakMap and WeakSet hold weak references to objects, meaning they don't prevent garbage collection. When the object they reference is deleted, the entry is automatically cleaned up.
WeakMap— keys must be objects, values can be anything. Not iterable.WeakSet— only stores objects. Not iterable, nosizeproperty.
Use case: Caching data associated with DOM nodes or objects without causing memory leaks. When the DOM node is removed, the cached data is automatically freed.
A Proxy wraps an object and lets you intercept and redefine fundamental operations on it — like property access, assignment, function calls, and more — using "traps".
Proxies power many frameworks' reactivity systems (like Vue 3's reactive()) and are used for validation, logging, access control, and lazy loading.
Promise.all, Promise.race, Promise.allSettled, and Promise.any.all for parallel requests that all must succeed. allSettled for parallel requests where you need all results regardless. race for timeouts. any for first-available fallback.Currying is a functional programming technique that transforms a function with multiple arguments into a sequence of functions, each taking a single argument.
Currying enables function reuse, cleaner code for repetitive operations, and is heavily used in functional programming and libraries like Ramda and Lodash/fp.
A memory leak occurs when memory that is no longer needed isn't released, causing the application to consume more and more RAM over time.
Common causes and fixes:
- Forgotten event listeners: Always call
removeEventListenerwhen a component unmounts or element is removed. - Global variables: Variables accidentally declared globally persist forever. Use
let/constand strict mode. - Closures holding large objects: A closure that references a large object keeps it in memory. Nullify references when done.
- Detached DOM nodes: Removing an element from the DOM but keeping a JavaScript reference to it prevents GC. Set references to
null. - setInterval not cleared: Always call
clearInterval()/clearTimeout()when no longer needed.
The JavaScript runtime has two task queues with different priorities:
- Microtask queue (higher priority): Promises (
.then,.catch),async/await,queueMicrotask(),MutationObserver. All microtasks are drained after each task before the next macrotask runs. - Macrotask queue (lower priority):
setTimeout,setInterval,setImmediate, I/O events, UI rendering.
More Interview Questions Coming
We're building Q&A pages for React, Python, Git, CSS, and more. Bookmark RankWeb3 and check back — new pages drop every week.
Browse All Articles →