30
Total Questions
10
Beginner
12
Intermediate
8
Advanced

🌱 Beginner Questions Q1–Q10

1
What is JavaScript and why is it used?
BeginnerVery Common
+

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
💡Why interviewers ask this: To check your foundational understanding. Keep your answer concise and mention the browser + Node.js distinction to show broader knowledge.
2
What is the difference between var, let, and const?
BeginnerVery Common
+

This is one of the most asked JavaScript questions. The three keywords differ in scope, hoisting behaviour, and reassignment rules.

JavaScript
var x = 10; // Function-scoped, hoisted, can be redeclared let y = 20; // Block-scoped, hoisted (TDZ), cannot be redeclared const z = 30; // Block-scoped, must be initialised, cannot be reassigned // var leaks out of blocks: if (true) { var a = 1; } console.log(a); // 1 ✓ (var leaked out) // let stays inside the block: if (true) { let b = 2; } console.log(b); // ReferenceError ✗

In modern JavaScript, prefer const by default. Use let only when you need to reassign the variable. Avoid var in new code.

💡Why interviewers ask this: It tests whether you understand scope and hoisting. Mention the Temporal Dead Zone (TDZ) for let/const to impress the interviewer.
3
What is the difference between == and === in JavaScript?
BeginnerVery Common
+

== 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.

JavaScript
0 == '' // true (coercion: '' → 0) 0 === '' // false (different types) null == undefined // true null === undefined // false '5' == 5 // true (string coerced to number) '5' === 5 // false

Always prefer === in real code to avoid unexpected bugs caused by implicit type coercion.

4
What are the data types in JavaScript?
Beginner
+

JavaScript has 8 data types, divided into two categories:

Primitive types (7): stored by value

  • String — text: "hello"
  • Number — integers and floats: 42, 3.14
  • BigInt — very large integers: 9007199254740991n
  • Booleantrue or false
  • undefined — declared but not assigned
  • null — intentional absence of value
  • Symbol — unique identifier (ES6+)

Non-primitive (1): stored by reference

  • Object — includes arrays, functions, dates, etc.
💡Common trap: typeof null returns "object" — this is a well-known JavaScript bug that has never been fixed for backwards compatibility reasons. Mentioning this shows depth.
5
What is hoisting in JavaScript?
BeginnerVery Common
+

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.

JavaScript
// Function declaration — fully hoisted: console.log(greet()); // "Hello" ✓ — works before definition function greet() { return "Hello"; } // var — hoisted but initialised as undefined: console.log(name); // undefined (not an error) var name = "Meraj"; // let/const — hoisted but NOT initialised (TDZ): console.log(age); // ReferenceError ✗ let age = 25;

Only declarations are hoisted — not initialisations. Function declarations are fully hoisted; function expressions are not.

6
What is the difference between null and undefined?
Beginner
+

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.
JavaScript
let x; console.log(x); // undefined (auto-set by JS) console.log(typeof x); // "undefined" let y = null; console.log(y); // null (manually set) console.log(typeof y); // "object" ← famous JS quirk! console.log(x == y); // true (loose equality) console.log(x === y); // false (strict equality)
7
What are arrow functions and how do they differ from regular functions?
BeginnerVery Common
+

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.

JavaScript
// Regular function function add(a, b) { return a + b; } // Arrow function (equivalent) const add = (a, b) => a + b; // Arrow functions inherit `this` from surrounding scope: const obj = { name: "RankWeb3", regularFn: function() { return this.name; }, // "RankWeb3" arrowFn: () => this.name // undefined (this = outer scope) };
  • Arrow functions cannot be used as constructors (no new)
  • Arrow functions have no arguments object
  • Best used for callbacks and non-method functions
8
What is a template literal in JavaScript?
Beginner
+

Template literals (ES6) are string literals that allow embedded expressions and multi-line strings using backticks (` `) instead of quotes.

JavaScript
const name = "Meraj"; const role = "developer"; // Old way (string concatenation): "Hello, " + name + "! You are a " + role + "."; // Template literal (cleaner): `Hello, ${name}! You are a ${role}.`; // Multi-line string: const msg = `Line 1 Line 2 Line 3`;
9
What is the difference between forEach and map?
BeginnerCommon
+

Both iterate over arrays, but the key difference is what they return:

  • forEach — executes a function on each element. Returns undefined. Used for side effects.
  • map — creates and returns a new array of transformed values. Does not mutate the original.
JavaScript
const nums = [1, 2, 3]; // forEach — no return value: nums.forEach(n => console.log(n * 2)); // 2, 4, 6 (logged) const r1 = nums.forEach(n => n * 2); console.log(r1); // undefined // map — returns new array: const r2 = nums.map(n => n * 2); console.log(r2); // [2, 4, 6]

Use map when you need the transformed values. Use forEach when you just need to run something for each item (logging, DOM updates, etc.).

10
What is destructuring in JavaScript?
Beginner
+

Destructuring is an ES6 syntax that lets you unpack values from arrays or properties from objects into separate variables in a single line.

JavaScript
// Array destructuring: const [a, b, c] = [1, 2, 3]; console.log(a, b, c); // 1 2 3 // Object destructuring: const user = { name: "Meraj", role: "dev", age: 25 }; const { name, role } = user; console.log(name, role); // "Meraj" "dev" // Rename while destructuring: const { name: userName } = user; console.log(userName); // "Meraj" // Default values: const { country = "India" } = user; console.log(country); // "India"

Intermediate Questions Q11–Q22

11
What is a closure in JavaScript?
IntermediateVery Common
+

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.

JavaScript
function makeCounter() { let count = 0; // outer variable return function() { count++; // inner function accesses outer variable return count; }; } const counter = makeCounter(); console.log(counter()); // 1 console.log(counter()); // 2 console.log(counter()); // 3 // count persists between calls!

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.

💡Why interviewers ask this: Closures come up in almost every mid-to-senior JS interview. Be ready to write a closure from scratch, not just define it.
12
What is the JavaScript Event Loop?
IntermediateVery Common
+

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.
JavaScript
console.log("1"); // Sync setTimeout(() => console.log("2"), 0); // Macro-task queue Promise.resolve().then(() => console.log("3")); // Microtask queue console.log("4"); // Sync // Output: 1 → 4 → 3 → 2 // Microtasks (Promises) always run before macro-tasks (setTimeout)
13
What is a Promise in JavaScript?
IntermediateVery Common
+

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states: pending, fulfilled, or rejected.

JavaScript
const fetchData = new Promise((resolve, reject) => { const success = true; if (success) { resolve("Data loaded!"); } else { reject(new Error("Failed to load")); } }); fetchData .then(data => console.log(data)) // "Data loaded!" .catch(err => console.log(err)) // handles rejection .finally(() => console.log("Done")); // always runs

Promises replaced callback-based async patterns and enabled the cleaner async/await syntax built on top of them.

14
What is async/await and how does it work?
IntermediateVery Common
+

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.

JavaScript
// Promise chain (old way): fetch('/api/user') .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.log(err)); // async/await (cleaner): async function getUser() { try { const res = await fetch('/api/user'); const data = await res.json(); console.log(data); } catch (err) { console.log(err); } }
💡Key point: await only pauses the async function — not the whole program. The event loop continues running other code while waiting.
15
What is event delegation in JavaScript?
Intermediate
+

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.

JavaScript
// ❌ Without delegation — listeners on each button: document.querySelectorAll('button').forEach(btn => { btn.addEventListener('click', handleClick); }); // ✅ With delegation — one listener on parent: document.querySelector('#btn-container') .addEventListener('click', (e) => { if (e.target.matches('button')) { handleClick(e); } });

Benefits: fewer event listeners = better memory usage; works on dynamically added elements; cleaner code.

16
What is the spread operator and rest parameter?
Intermediate
+

Both use the ... syntax but serve opposite purposes:

JavaScript
// Spread — EXPANDS an iterable into individual elements: const a = [1, 2]; const b = [3, 4]; const c = [...a, ...b]; // [1, 2, 3, 4] const obj1 = { x: 1 }; const obj2 = { ...obj1, y: 2 }; // { x: 1, y: 2 } // Rest — COLLECTS remaining arguments into an array: function sum(first, ...rest) { return first + rest.reduce((a, b) => a + b, 0); } sum(1, 2, 3, 4); // 10
17
What is this in JavaScript and how does its value get determined?
IntermediateVery Common
+

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) or global (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
JavaScript
const obj = { name: "RankWeb3", greet() { return this.name; } // "RankWeb3" }; const fn = obj.greet; fn(); // undefined — lost context! fn.call(obj); // "RankWeb3" — context restored
18
What is the difference between call, apply, and bind?
Intermediate
+

All three methods explicitly set the this value for a function, but they differ in how and when the function executes:

JavaScript
function introduce(lang, year) { return `${this.name} knows ${lang} since ${year}`; } const dev = { name: "Meraj" }; // call — invokes immediately, args passed individually: introduce.call(dev, "JS", 2022); // apply — invokes immediately, args passed as array: introduce.apply(dev, ["JS", 2022]); // bind — returns a NEW function with bound `this`: const boundFn = introduce.bind(dev); boundFn("JS", 2022); // call later
19
What is shallow copy vs deep copy?
Intermediate
+

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.

JavaScript
const original = { a: 1, nested: { b: 2 } }; // Shallow copy — spread operator: const shallow = { ...original }; shallow.nested.b = 99; console.log(original.nested.b); // 99 — original was mutated! // Deep copy — structuredClone (modern, recommended): const deep = structuredClone(original); deep.nested.b = 99; console.log(original.nested.b); // 2 — original is safe ✓

Other deep copy methods: JSON.parse(JSON.stringify(obj)) (has limitations with functions/dates), or libraries like Lodash's _.cloneDeep.

20
What is debouncing and throttling?
IntermediateCommon
+

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.
JavaScript
// Debounce — fires 300ms after last call: function debounce(fn, delay) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; } const onSearch = debounce((query) => fetchResults(query), 300);
💡Memory tip: Debounce = waits for silence (like a mic). Throttle = limits rate (like a water valve).
21
What are JavaScript modules (import / export)?
Intermediate
+

ES6 modules allow you to split code into separate files and share functionality between them using export and import.

JavaScript
// math.js — named exports: export const add = (a, b) => a + b; export const sub = (a, b) => a - b; // math.js — default export: export default function multiply(a, b) { return a * b; } // app.js — importing: import multiply, { add, sub } from './math.js'; // Import everything as a namespace: import * as Math from './math.js'; Math.add(2, 3); // 5
22
What is memoization?
Intermediate
+

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.

JavaScript
function memoize(fn) { const cache = {}; return function(...args) { const key = JSON.stringify(args); if (cache[key] !== undefined) { return cache[key]; // return cached result } cache[key] = fn(...args); return cache[key]; }; } const slowSquare = (n) => { /* expensive calc */ return n * n; }; const fastSquare = memoize(slowSquare); fastSquare(10); // computed: 100 fastSquare(10); // cached: 100 (instant)

🔥 Advanced Questions Q23–Q30

23
What is prototypal inheritance in JavaScript?
Advanced
+

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.

JavaScript
const animal = { speak() { return `${this.name} makes a sound`; } }; const dog = Object.create(animal); dog.name = "Rex"; console.log(dog.speak()); // "Rex makes a sound" // speak() was found on the prototype, not dog itself // Check the chain: console.log(Object.getPrototypeOf(dog) === animal); // true

ES6 class syntax is built on top of prototypal inheritance — it's syntactic sugar that doesn't change the underlying prototype-based model.

24
What are Generators and how do they work?
Advanced
+

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.

JavaScript
function* counter() { let i = 0; while (true) { yield i++; // pause here and return i } } const gen = counter(); console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2

Generators are useful for lazy evaluation, infinite sequences, and were the foundation for async/await before it was natively supported.

25
What are WeakMap and WeakSet and when would you use them?
Advanced
+

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, no size property.
JavaScript
const cache = new WeakMap(); let user = { name: "Meraj" }; cache.set(user, { lastLogin: "2026" }); console.log(cache.get(user)); // { lastLogin: "2026" } user = null; // object eligible for GC // cache entry is automatically removed — no memory leak

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.

26
What is the Proxy object in JavaScript?
Advanced
+

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".

JavaScript
const user = { name: "Meraj", age: 25 }; const validatedUser = new Proxy(user, { set(target, key, value) { if (key === "age" && typeof value !== "number") { throw new TypeError("Age must be a number"); } target[key] = value; return true; } }); validatedUser.age = 30; // ✓ validatedUser.age = "old"; // ✗ TypeError thrown

Proxies power many frameworks' reactivity systems (like Vue 3's reactive()) and are used for validation, logging, access control, and lazy loading.

27
Explain Promise.all, Promise.race, Promise.allSettled, and Promise.any.
AdvancedCommon
+
JavaScript
const p1 = Promise.resolve(1); const p2 = Promise.resolve(2); const pFail = Promise.reject("error"); // all — waits for ALL. Rejects if ANY fails: await Promise.all([p1, p2]); // [1, 2] await Promise.all([p1, pFail]); // throws "error" // allSettled — waits for ALL regardless of outcome: await Promise.allSettled([p1, pFail]); // [{status:"fulfilled",value:1}, {status:"rejected",reason:"error"}] // race — resolves/rejects with the FIRST to settle: await Promise.race([p1, p2]); // 1 (fastest) // any — resolves with FIRST success. Rejects only if ALL fail: await Promise.any([pFail, p2]); // 2
💡When to use which: 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.
28
What is currying in JavaScript?
Advanced
+

Currying is a functional programming technique that transforms a function with multiple arguments into a sequence of functions, each taking a single argument.

JavaScript
// Normal function: const add = (a, b, c) => a + b + c; add(1, 2, 3); // 6 // Curried version: const curriedAdd = a => b => c => a + b + c; curriedAdd(1)(2)(3); // 6 // Partial application (pre-fill some args): const addFive = curriedAdd(5); addFive(3)(2); // 10 addFive(10)(1); // 16

Currying enables function reuse, cleaner code for repetitive operations, and is heavily used in functional programming and libraries like Ramda and Lodash/fp.

29
What causes memory leaks in JavaScript and how do you prevent them?
Advanced
+

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 removeEventListener when a component unmounts or element is removed.
  • Global variables: Variables accidentally declared globally persist forever. Use let/const and 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.
💡Detection tool: Use Chrome DevTools → Memory tab → take heap snapshots before and after an action to find what objects are growing unexpectedly.
30
What is the difference between microtasks and macrotasks?
AdvancedCommon
+

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.
JavaScript
console.log("start"); setTimeout(() => console.log("macrotask"), 0); Promise.resolve() .then(() => console.log("microtask 1")) .then(() => console.log("microtask 2")); console.log("end"); // Output: // start // end // microtask 1 // microtask 2 // macrotask
💡Rule of thumb: After every macrotask (including the initial script), the engine empties the entire microtask queue before moving to the next macrotask.

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 →