JavaScript interviews reward understanding the machinery behind the syntax — why closures work, what the event loop actually does, why == and === behave differently. This covers all 100 questions, organized by topic, with real code, a diagram, and a mock test at the end.
JavaScript Fundamentals
Q1. What are the data types present in JavaScript?
| Category | Types |
|---|---|
| Primitive | string, number, bigint, boolean, undefined, symbol, null |
| Object | object (includes arrays, functions, dates — everything else) |
Primitives are immutable and compared by value; everything else is an object, compared by reference. typeof null famously returns "object" — a long-standing quirk from JavaScript's earliest implementation, not a meaningful design choice.
Q2. What is the difference between null and undefined?
| undefined | null | |
|---|---|---|
| Meaning | A variable has been declared but not assigned a value | The explicit, deliberate absence of a value |
| Set by | The JS engine automatically | Only ever set intentionally by code |
| typeof | "undefined" | "object" (a well-known historical quirk) |
Q3. How does JavaScript handle type coercion?
"5" + 3; // "53" — + prefers string concatenation if either operand is a string
"5" - 3; // 2 — - forces both operands to numbers
5 + true; // 6 — true coerces to 1
5 + null; // 5 — null coerces to 0
5 + undefined; // NaN — undefined coerces to NaNJavaScript automatically converts values between types when an operator expects a type that doesn't match what it was given — the rules aren't arbitrary (+ leans toward string concatenation, most other arithmetic operators force numeric conversion), but they're easy to get wrong from memory, which is exactly why === and explicit conversions (Number(), String()) are generally preferred over relying on implicit coercion.
Q4. Explain the concept of hoisting in JavaScript.
console.log(x); // undefined, not an error — the declaration is hoisted
var x = 5;
console.log(y); // ReferenceError — let/const are hoisted but not initialized
let y = 5;
sayHi(); // works — function declarations are fully hoisted
function sayHi() { console.log("hi"); }Hoisting is the JS engine's behavior of processing declarations before executing code line by line — var declarations are hoisted and initialized to undefined; let/const are hoisted but stay in an uninitialized "temporal dead zone" until their actual declaration line runs; function declarations are hoisted with their full body, which is why you can call a function defined later in the same file.
Q5. What is the scope in JavaScript?
| Scope type | Applies to | Introduced by |
|---|---|---|
| Global scope | Accessible everywhere | Declared outside any function/block |
| Function scope | Only within the function | var, function parameters |
| Block scope | Only within the enclosing {} | let, const |
Q6. What is the difference between == and ===?
"5" == 5; // true — == coerces types before comparing
"5" === 5; // false — === compares both value AND type, no coercion
null == undefined; // true
null === undefined; // false== performs type coercion before comparing, which produces surprising results often enough that === (strict equality — same value and same type, no coercion) is the near-universal default recommendation in modern JS style guides.
Q7. Describe closure in JavaScript. Can you give an example?
function makeCounter() {
let count = 0;
return function () {
count++; // still has access to 'count' after makeCounter returns
return count;
};
}
const counter = makeCounter();
counter(); // 1
counter(); // 2 — the SAME count variable persists across callsA closure is a function that retains access to variables from its enclosing scope even after that outer function has finished executing — the inner function "closes over" count, keeping it alive in memory for as long as the closure itself exists. Closures are the mechanism behind private variables (before classes had real private fields), memoization, and much of functional-style JS.
Q8. What is the 'this keyword' and how does its context change?
const obj = {
name: "Ada",
greet() { console.log(this.name); } // 'this' is obj — called as obj.greet()
};
obj.greet(); // "Ada"
const greetFn = obj.greet;
greetFn(); // undefined (or throws in strict mode) — 'this' lost its binding
const arrow = () => console.log(this); // arrow functions don't have their own 'this' —
// they capture it from the enclosing scopethis refers to whatever object the function was called ON, not where it was defined — which is exactly why extracting a method and calling it standalone (greetFn() above) loses the intended this. Arrow functions deliberately don't have their own this at all; they inherit it lexically from the surrounding scope, which is why they're commonly used for callbacks that need to preserve an outer this.
Q9. What are arrow functions and how do they differ from regular functions?
| Regular function | Arrow function | |
|---|---|---|
| this binding | Dynamic — depends on how it's called | Lexical — inherited from the enclosing scope, fixed |
| arguments object | Available | Not available |
| Can be a constructor (new)? | Yes | No — throws an error |
| Syntax | function() {} | () => {} |
Q10. What are template literals in JavaScript?
const name = "Ada";
const greeting = `Hello, ${name}! Today is ${new Date().toDateString()}.`;
// Multi-line strings, no concatenation needed:
const html = `
<div>
<p>${name}</p>
</div>
`;Template literals (backtick-delimited strings) support embedded expressions (${...}) and multi-line text directly, without the string-concatenation gymnastics ('Hello, ' + name + '!') older syntax required.
JavaScript Functions and Higher-Order Functions
Q11. What is a higher-order function in JavaScript?
function withLogging(fn) {
return function (...args) {
console.log("calling with", args);
return fn(...args);
};
}
const loggedAdd = withLogging((a, b) => a + b);A higher-order function either takes a function as an argument, returns a function, or both — Array.prototype.map/filter/reduce are the most commonly used built-in examples, and withLogging above is a hand-rolled one wrapping any function with logging behavior.
Q12. Can functions be assigned as values to variables in JavaScript?
const add = function (a, b) { return a + b; };
const multiply = (a, b) => a * b;Yes — functions are first-class values in JavaScript, storable in variables, passable as arguments, and returnable from other functions, exactly like any other value (a number, a string, an object).
Q13. How do functional programming concepts apply in JavaScript?
const total = orders
.filter(o => o.status === "completed")
.map(o => o.amount)
.reduce((sum, amount) => sum + amount, 0);JavaScript supports (without strictly enforcing) functional patterns: pure functions, immutability (preferring new arrays/objects over mutation), and composing small functions (filter/map/reduce chains, as above) rather than imperative loops — first-class functions and closures are what make this style natural in JS.
Q14. What are IIFEs (Immediately Invoked Function Expressions)?
(function () {
const privateVar = "hidden";
console.log("runs immediately");
})();An IIFE is a function defined and called in the same expression — historically used to create an isolated scope avoiding global namespace pollution, before block-scoped let/const and ES modules made that pattern far less necessary in modern code.
Q15. How do you create private variables in JavaScript?
class Counter {
#count = 0; // true private field (ES2022)
increment() { return ++this.#count; }
}
const c = new Counter();
c.increment(); // 1
c.#count; // SyntaxError — genuinely inaccessible from outsideBefore ES2022's # private fields, privacy was simulated via closures (a variable captured inside a function/module, never exposed) — # fields now give classes actual language-enforced privacy, not just a convention.
JavaScript Objects and Prototypes
Q16. How do you create an object in JavaScript?
const obj1 = { name: "Ada" }; // object literal
const obj2 = new Object(); // constructor
const obj3 = Object.create(null); // no prototype at all
class Person { constructor(name) { this.name = name; } }
const obj4 = new Person("Ada"); // via a classQ17. What are prototypes in JavaScript?
Every object has an internal link (its prototype) to another object it inherits properties/methods from — when a property lookup fails on the object itself, JavaScript walks up the prototype chain checking each linked object in turn, until it finds the property or reaches the end of the chain (null).
Q18. Explain prototypal inheritance.
const animal = { speak() { console.log("..."); } };
const dog = Object.create(animal); // dog's prototype is animal
dog.bark = function () { console.log("Woof"); };
dog.speak(); // inherited via the prototype chain
dog.bark(); // dog's own propertyObjects inherit directly from other objects (not from "classes" in the classical sense) — class syntax in modern JS is syntactic sugar over this same prototype mechanism, not a fundamentally different inheritance model underneath.
Q19. What is the difference between object literals and constructor functions?
| Object literal | Constructor function | |
|---|---|---|
| Creates | Exactly one object | A reusable template for many instances |
| Reuse | Copy-paste for another instance | new Person("Ada"), new Person("Grace")... |
| Shared behavior | Duplicated per object unless manually shared | Methods live on the prototype, shared by every instance |
Q20. How do you add or remove properties from an object?
const obj = { name: "Ada" };
obj.age = 36; // add
obj["email"] = "a@b.com"; // add (bracket notation)
delete obj.age; // removeAsynchronous JavaScript
Q21. What is the event loop in JavaScript?
JavaScript itself is single-threaded — one call stack, one thing running at a time. The event loop is what allows non-blocking async behavior anyway: a slow operation (a timer, a network request) is handed off to the browser/Node's Web APIs, and once it completes, its callback is queued and the event loop pulls it back onto the call stack only once the stack is empty — which is why a setTimeout(fn, 0) still runs after all currently-queued synchronous code.
Q22. Explain how callbacks work in JavaScript.
function fetchUser(id, callback) {
setTimeout(() => callback({ id, name: "Ada" }), 1000);
}
fetchUser(1, (user) => console.log(user.name));A callback is a function passed into another function, invoked once that function's work (often asynchronous) completes — the original mechanism for async JS, superseded in most modern code by Promises/async-await specifically because deeply nested callbacks ("callback hell") become hard to read and reason about.
Q23. What are promises and how do they manage asynchronous code?
function fetchUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve({ id, name: "Ada" }), 1000);
});
}
fetchUser(1)
.then(user => console.log(user.name))
.catch(err => console.error(err));A Promise represents a value that will eventually be available (or fail) — pending, fulfilled, or rejected — and .then()/.catch() chain callbacks onto it flatly, instead of nesting them ever deeper the way plain callbacks require for sequential async steps.
Q24. Explain async/await in JavaScript and how it differs from Promises.
async function getUser(id) {
try {
const user = await fetchUser(id); // pauses here until the promise resolves
console.log(user.name);
} catch (err) {
console.error(err);
}
}async/await is syntactic sugar over Promises — it lets asynchronous code read like synchronous code (top-to-bottom, with try/catch for errors) while an async function still returns a Promise underneath, and await still suspends without blocking the actual JS thread. It doesn't replace Promises; it's a nicer syntax for consuming them.
Q25. What is the Job Queue (or Microtask Queue)?
| Queue | Contains | Priority |
|---|---|---|
| Microtask queue | Promise callbacks (.then/.catch), queueMicrotask | Drained completely before the next macrotask |
| Macrotask ("task") queue | setTimeout, setInterval, I/O callbacks | One task per event loop tick |
Microtasks always run before the next macrotask, even one scheduled earlier — this is why a Promise's .then() callback runs before a setTimeout(fn, 0) callback, even though both were "queued" around the same moment; the microtask queue is fully drained first, every time.
DOM Manipulation and Browser APIs
Q26. How do you select DOM elements using JavaScript?
document.getElementById("main");
document.querySelector(".card"); // first match
document.querySelectorAll(".card"); // all matches, a NodeListQ27. Explain event propagation in the DOM.
| Phase | Direction |
|---|---|
| Capturing | From the document root DOWN to the target element |
| Target | The element the event actually occurred on |
| Bubbling | From the target back UP to the document root (the default for most event listeners) |
An event doesn't just fire on its target — it propagates through the DOM tree, which is exactly what makes event delegation possible: a listener on a parent element can react to events that actually occurred on any of its descendants, by observing them during the bubbling phase.
Q28. How do you prevent a form from submitting using JavaScript?
form.addEventListener("submit", (e) => {
e.preventDefault();
// handle the submission manually (validation, fetch, etc.)
});Q29. What are Web APIs in the context of JavaScript?
Web APIs (fetch, localStorage, DOM manipulation, geolocation, WebSockets) are provided by the browser, not by the JavaScript language itself — the ECMAScript spec defines the core language (syntax, types, closures), while the browser (or Node.js, for its own set of APIs) provides the environment-specific capabilities layered on top.
Q30. How can you manipulate the browser history using JavaScript?
history.pushState({ page: 2 }, "", "/page2"); // adds a new entry, no reload
history.back();
window.addEventListener("popstate", (e) => console.log(e.state));ES2015+ and Modern JavaScript Features
Q31. What are the new features introduced in ES6?
- let/const, arrow functions, template literals, classes
- Destructuring, default parameters, the spread/rest operator
- Promises, native modules (import/export)
- Map, Set, and their WeakMap/WeakSet variants
Q32. How do you use destructuring assignments in ES6?
const { name, age = 18 } = person; // object destructuring, with a default
const [first, second, ...rest] = numbers; // array destructuring with rest
function greet({ name, greeting = "Hello" }) {
console.log(`${greeting}, ${name}`);
}Q33. Explain the use of const and let keywords.
| var | let | const | |
|---|---|---|---|
| Scope | Function-scoped | Block-scoped | Block-scoped |
| Reassignable? | Yes | Yes | No (though object/array contents can still mutate) |
| Hoisting behavior | Hoisted, initialized to undefined | Hoisted, in temporal dead zone until declared | Same as let |
Q34. What are default parameters in JavaScript functions?
function greet(name = "Guest") {
console.log(`Hello, ${name}`);
}
greet(); // "Hello, Guest"
greet("Ada"); // "Hello, Ada"Q35. Explain the concept of modules in ES6.
// math.js
export function add(a, b) { return a + b; }
export default class Calculator { }
// app.js
import Calculator, { add } from "./math.js";ES modules give JavaScript native, standardized import/export syntax — each module has its own scope by default (no accidental global leakage), explicit dependencies declared at the top of the file, and static analysis (bundlers can determine what's used at build time, enabling tree-shaking of unused exports).
Event Handling
Q36. How do you handle events in JavaScript?
button.addEventListener("click", (event) => {
console.log("Clicked!", event.target);
});Q37. What is event delegation and why is it useful?
list.addEventListener("click", (e) => {
if (e.target.matches("li")) {
console.log("Clicked item:", e.target.textContent);
}
});
// One listener handles clicks on every <li>, even ones added to the DOM laterInstead of attaching a listener to every individual child element, attach one listener to a shared parent and check event.target inside it — fewer listeners overall (better for performance/memory with long lists), and it automatically covers elements added dynamically after the listener was set up, which per-element listeners wouldn't.
Q38. How do you add and remove an event listener from an element?
function handleClick() { console.log("clicked"); }
button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick);
// Must be the SAME function reference — an anonymous function passed inline can't be removed laterQ39. Can you explain how 'this' works in event handlers?
button.addEventListener("click", function () {
console.log(this); // 'this' is the button element itself
});
button.addEventListener("click", () => {
console.log(this); // an arrow function — 'this' is whatever the ENCLOSING scope's 'this' is, NOT the button
});Q40. What is the difference between event.preventDefault() and event.stopPropagation()?
| preventDefault() | stopPropagation() | |
|---|---|---|
| Stops | The browser's default action (form submit, link navigation) | The event from continuing to bubble/capture to other listeners |
| Doesn't affect | Event propagation to other listeners | The default browser action |
Web Storage and Security
Q41. What is the difference between localStorage, sessionStorage, and cookies?
| localStorage | sessionStorage | Cookies | |
|---|---|---|---|
| Persistence | Until explicitly cleared | Until the tab/window closes | Until expiry (configurable) |
| Sent to server? | No — client-only | No — client-only | Yes — sent with every matching request |
| Capacity | ~5-10MB | ~5-10MB | ~4KB |
Q42. Can you explain Cross-Site Scripting (XSS) and how to prevent it?
Covered in depth in the 100 Web Security interview questions post — injecting malicious script that executes in another user's browser session, prevented primarily by escaping/encoding all rendered output and relying on a framework's default auto-escaping rather than raw innerHTML assignment of untrusted content.
Q43. What is Cross-Origin Resource Sharing (CORS) and how does it work?
Access-Control-Allow-Origin: https://myapp.com
Access-Control-Allow-Methods: GET, POSTCORS is a header-based mechanism letting a server explicitly opt in to being called from a different origin — without it, the browser's Same-Origin Policy blocks a script running on one origin from reading a response from another. For non-trivial requests, the browser sends a preflight OPTIONS request first to check what's allowed before sending the real one.
Q44. How does content security policy (CSP) help in preventing security attacks?
Covered in depth in the Web Security post — CSP lets a page declare an allow-list of sources it trusts for scripts/styles/etc., so even a successful XSS injection can be blocked from executing (or from exfiltrating stolen data to an attacker's server) if the injected content's source isn't on that list.
JavaScript Debugging
Q45. What tools and techniques do you use for debugging JavaScript code?
- Browser DevTools — breakpoints, the console, the Network/Performance tabs
- console.log/table/group for quick inline inspection without a full debugger session
- Source maps to debug against original (unminified/untranspiled) source in production
Q46. How do you debug a JavaScript application in the browser?
Open DevTools (F12), set breakpoints directly in the Sources panel, use the debugger; statement to trigger a break programmatically, and step through execution watching variable values in the scope panel — the same interactive debugging workflow as any language's IDE debugger, just browser-native.
Q47. Explain the concept and use of breakpoints.
A breakpoint pauses execution at a specific line, letting you inspect the current call stack and variable state before stepping further — conditional breakpoints (pause only when an expression is true) and logpoints (log a value without actually pausing) extend the basic idea for more targeted debugging.
Q48. How do you handle exceptions in JavaScript?
try {
JSON.parse(invalidJson);
} catch (err) {
console.error("Parse failed:", err.message);
} finally {
cleanup();
}Performance and Optimization
Q49. What techniques can be used to improve JavaScript performance?
- Debounce/throttle expensive handlers (scroll, resize, input) instead of running them on every single event
- Avoid unnecessary DOM reads/writes interleaved (causes forced layout thrashing) — batch reads, then batch writes
- Lazy-load code/data not needed for the initial render
- Use efficient data structures (a Map/Set for lookups instead of scanning an array repeatedly)
Q50. How does JavaScript minification and bundling contribute to performance?
Minification strips whitespace/comments and shortens variable names, reducing file size (and therefore download time); bundling combines many files into fewer, larger ones, reducing the number of separate HTTP requests a browser has to make — both are standard build-step optimizations for production, generally skipped in development for readable debugging.
Q51. Discuss the importance of web page loading time and performance.
Slower load times measurably increase bounce rate and hurt conversion — and Core Web Vitals (load, interactivity, visual stability metrics) directly factor into search ranking too, so performance is both a user-experience and a business/SEO concern, not just an engineering nicety.
Q52. Explain how lazy loading works in JavaScript.
const module = await import("./heavy-feature.js"); // loaded only when actually needed
<img src="photo.jpg" loading="lazy" /> // native browser lazy-loading for imagesLazy loading defers fetching code or assets until they're actually needed — a dynamic import() splits that code into a separate chunk downloaded on demand, and the native loading="lazy" attribute defers off-screen images until they're about to scroll into view, both reducing what has to load upfront.
JavaScript Testing
Q53. What are some JavaScript testing frameworks you know?
| Framework | Notes |
|---|---|
| Jest | Widely used, batteries-included (assertions, mocking, coverage) |
| Vitest | Vite-native, Jest-compatible API, fast |
| Mocha + Chai | Older, more modular — pick your own assertion/mocking libraries |
| Cypress / Playwright | End-to-end/browser-automation testing, not unit testing |
Q54. How can you write unit tests for JavaScript code?
function add(a, b) { return a + b; }
test("adds two numbers", () => {
expect(add(2, 3)).toBe(5);
});Q55. What is Test-Driven Development (TDD) in JavaScript?
Write a failing test first, write the minimum code to pass it, then refactor — the same red-green-refactor cycle covered in depth in the SQL and .NET Core interview posts' respective sections, applied to JS with Jest/Vitest instead of xUnit.
Q56. Can you explain the difference between unit and integration testing?
A unit test isolates one function/component (mocking its dependencies); an integration test exercises real collaboration between multiple pieces — a component actually rendering with its real child components, or a function actually calling a real (test) API — catching the bugs that only show up at the seams between units.
Networking with JavaScript
Q57. How do you make HTTP requests in JavaScript?
const response = await fetch("https://api.example.com/users");
const users = await response.json();Q58. What is the difference between XMLHttpRequest and Fetch API?
| XMLHttpRequest | Fetch API | |
|---|---|---|
| API style | Callback/event-based, verbose | Promise-based, concise |
| Status | Legacy — still works, rarely written by hand today | The modern standard for HTTP requests |
| Streaming | Supported, awkward API | Supported via ReadableStream, cleaner |
Q59. What is AJAX, and how does it work?
AJAX (Asynchronous JavaScript and XML — the name predates JSON's dominance, but the term stuck) is the technique of making HTTP requests from JavaScript without a full page reload, updating only part of the page with the response — originally via XMLHttpRequest, now almost always via fetch.
Q60. How do you use WebSockets in a web application?
const socket = new WebSocket("wss://example.com/chat");
socket.onopen = () => socket.send("Hello!");
socket.onmessage = (event) => console.log("Received:", event.data);WebSockets establish a persistent, full-duplex connection between client and server — unlike HTTP's request-response model, either side can push a message at any time, which is what makes them the right fit for chat, live notifications, and real-time collaborative features.
JavaScript Patterns and Best Practices
Q61. What is a design pattern in JavaScript?
A reusable solution to a recurring design problem — Module, Singleton, Observer, Factory — the same general design-patterns vocabulary covered in depth (with code examples) in the 52 OOP interview questions post, applied through JavaScript's specific language features (closures, prototypes, first-class functions).
Q62. Can you explain the module pattern?
const Counter = (function () {
let count = 0; // private, inaccessible from outside
return {
increment() { return ++count; },
reset() { count = 0; },
};
})();The module pattern uses an IIFE's closure to create private state, exposing only a deliberately chosen public interface — the pre-ES6-modules way of achieving encapsulation, largely superseded today by native ES modules (each file has its own scope automatically) but still a useful pattern to recognize in older code.
Q63. What is the Singleton pattern in JavaScript?
const AppConfig = (function () {
let instance;
function create() { return { theme: "dark" }; }
return { getInstance: () => instance || (instance = create()) };
})();Q64. Explain the Revealing Module pattern.
const Calculator = (function () {
function add(a, b) { return a + b; }
function subtract(a, b) { return a - b; }
return { add, subtract }; // explicitly "reveals" which internal functions are public
})();A variation on the module pattern where every function is defined privately first, and the return statement explicitly lists which ones become public — making the public API more readable at a glance than mixing public/private definitions inline.
Q65. What are some best practices for coding in JavaScript?
- Prefer const by default, let only when reassignment is genuinely needed, and avoid var entirely in new code
- Use === over == to avoid coercion surprises
- Keep functions small and focused — easier to test and reason about
- Handle promise rejections explicitly (.catch, or try/catch around await) rather than letting them fail silently
JavaScript Algorithms and Data Structures
Q66. How do you implement a stack and a queue in JavaScript?
// Stack (LIFO) — array's push/pop work naturally
const stack = [];
stack.push(1); stack.push(2);
stack.pop(); // 2
// Queue (FIFO) — push/shift (shift is O(n), a real perf cost for large queues)
const queue = [];
queue.push(1); queue.push(2);
queue.shift(); // 1Q67. Explain how to sort an array in JavaScript.
[3, 1, 2].sort(); // [1, 2, 3] — default: lexicographic on stringified elements!
[10, 2, 1].sort(); // [1, 10, 2] — the classic gotcha
[10, 2, 1].sort((a, b) => a - b); // [1, 2, 10] — correct numeric sortArray.prototype.sort() mutates in place and, without a comparator, sorts elements as strings — a well-known gotcha for numeric arrays. Always pass an explicit comparator ((a, b) => a - b for ascending numbers) rather than relying on the default.
Q68. How do you check if a string is a palindrome?
function isPalindrome(str) {
const clean = str.toLowerCase().replace(/[^a-z0-9]/g, "");
return clean === clean.split("").reverse().join("");
}Q69. Describe a recursive function and provide an example.
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}A recursive function calls itself with a progressively smaller/simpler input until it reaches a base case that stops the recursion — natural for problems with a self-similar structure (tree traversal, factorial, Fibonacci), though deep recursion in JS can hit the call stack size limit for very large inputs, where an iterative approach would be safer.
Q70. What is the time complexity of JavaScript operations?
| Operation | Time complexity |
|---|---|
| array[i] (index access) | O(1) |
| array.push() / pop() | O(1) |
| array.shift() / unshift() | O(n) — every remaining element shifts |
| object[key] / Map.get(key) | O(1) average |
| array.includes() / indexOf() | O(n) — linear scan |
JavaScript Libraries and Frameworks
Q71. What is the difference between a library and a framework in JavaScript?
| Library | Framework | |
|---|---|---|
| Control flow | Your code calls the library when needed | The framework calls your code (inversion of control) |
| Example | lodash, axios | React, Angular, Vue |
Q72. Explain the Virtual DOM in React.
Covered in depth in the React interview prep post on this site's blog — React keeps a lightweight, in-memory representation of the UI, diffs it against the previous version on state changes, and applies only the minimal set of real DOM mutations needed, since real DOM operations are far more expensive than comparing plain JS objects.
Q73. How does data binding work in Angular?
<input [(ngModel)]="name" /> <!-- two-way binding: the input updates `name`, and vice versa -->
<p>{{ name }}</p> <!-- one-way, from component to view -->Angular supports both one-way binding ({{ expression }}, [property]) and two-way binding ([(ngModel)]) — two-way binding keeps a component property and a form input automatically synchronized in both directions, unlike React's typically one-way, explicit-state-update model.
Q74. What is Vue.js and what sets it apart from other frameworks?
Vue is a progressive framework — adoptable incrementally (drop a <script> tag into an existing page, or scale up to a full SFC-based SPA), with a template syntax closer to plain HTML than JSX, and a reactivity system that automatically tracks which parts of the UI depend on which data, re-rendering precisely what changed.
Q75. Can you describe the jQuery library and its applications?
jQuery simplified DOM manipulation, event handling, and AJAX requests across inconsistent early-2000s browser implementations with one unified API — largely unnecessary today since modern browsers standardized those APIs and native fetch/querySelector cover most of what jQuery existed to smooth over, but still found maintaining large legacy codebases built on it.
JavaScript ES2017+ and Beyond
Q76. What are async iterators and generators?
async function* fetchPages() {
let page = 1;
while (true) {
const data = await fetch(`/api/items?page=${page++}`);
const items = await data.json();
if (items.length === 0) return;
yield items;
}
}
for await (const items of fetchPages()) {
console.log(items);
}A generator (function*) can pause and resume execution, yielding a sequence of values over time rather than returning one value all at once; an async generator (async function*) combines that with await, useful for lazily streaming paginated data one page at a time, consumed with for await...of.
Q77. What is the purpose of the async keyword?
Marking a function async guarantees it always returns a Promise (wrapping the return value if it isn't already one) and enables await inside it — covered in depth in the Asynchronous JavaScript section above.
Q78. Can you explain the use of Object.entries() and Object.values()?
const person = { name: "Ada", age: 36 };
Object.keys(person); // ["name", "age"]
Object.values(person); // ["Ada", 36]
Object.entries(person); // [["name", "Ada"], ["age", 36]]
for (const [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`);
}Q79. How does JavaScript Handle big integers (BigInt)?
const big = 9007199254740993n; // the 'n' suffix marks a BigInt literal
const also = BigInt("9007199254740993");
Number.MAX_SAFE_INTEGER; // 9007199254740991 — regular numbers lose precision beyond thisRegular JS numbers are IEEE 754 doubles, which can't exactly represent every integer beyond Number.MAX_SAFE_INTEGER — BigInt (ES2020) is a separate numeric type supporting arbitrary-precision integers, useful for cryptography, precise large-number arithmetic, and IDs from systems (like 64-bit database keys) that exceed safe-integer range.
Q80. What are dynamic imports in JavaScript?
button.addEventListener("click", async () => {
const { renderChart } = await import("./chart.js"); // loaded only when clicked
renderChart();
});import() (as opposed to the static import at the top of a file) loads a module on demand at runtime, returning a Promise — the mechanism behind code-splitting: a heavy feature's code isn't downloaded at all until the user actually triggers the action that needs it.
Browser Compatibility and Transpilation
Q81. How do you ensure your JavaScript code is cross-browser compatible?
- Transpile modern syntax down to a broadly-supported target (via Babel) for the browsers you actually need to support
- Use polyfills for missing APIs (not syntax) in older browsers
- Check MDN/caniuse.com for actual support data before relying on a newer feature
- Test in real target browsers, not just assume transpilation covers every gap
Q82. What is Babel and how is it used in JavaScript development?
Babel transpiles modern JS syntax (optional chaining, newer class features, JSX) into an older, more widely-supported syntax equivalent — it changes syntax, not runtime capability, which is exactly why it's paired with polyfills for genuinely missing APIs (like fetch on very old browsers) that transpilation alone can't provide.
Q83. What are polyfills, and when would you use them?
if (!Array.prototype.includes) {
Array.prototype.includes = function (value) {
return this.indexOf(value) !== -1;
};
}A polyfill implements a missing API in plain JS so older environments that lack it natively can still use the same code — used when you need an actual runtime feature (a method, an API) an older target browser simply doesn't have, as opposed to Babel's job of translating newer syntax the parser itself wouldn't understand.
JavaScript and the DOM
Q84. What is the Document Object Model (DOM)?
The DOM is the browser's in-memory, object-based representation of an HTML document — a tree of nodes JavaScript can read and modify, and changes to it are what the browser actually re-renders on screen. It's not part of the JavaScript language itself; it's a Web API the browser exposes.
Q85. How do you create, append, or remove an element from the DOM?
const div = document.createElement("div");
div.textContent = "Hello";
document.body.appendChild(div);
div.remove(); // modern, direct removal
// older equivalent: div.parentNode.removeChild(div);Q86. Describe different ways to find or access HTML elements in the DOM.
| Method | Returns |
|---|---|
| getElementById(id) | A single element, or null |
| getElementsByClassName / TagName | A live HTMLCollection |
| querySelector(selector) | The first match for any CSS selector |
| querySelectorAll(selector) | A static NodeList of every match |
Q87. Explain the difference between innerHTML and textContent.
el.innerHTML = "<b>bold</b>"; // parsed as HTML — XSS risk if the source is untrusted
el.textContent = "<b>bold</b>"; // rendered as literal, escaped textinnerHTML parses its assigned string as HTML markup (a real XSS risk if that string ever contains untrusted user input); textContent treats it as plain text, always escaped — as a rule, use textContent unless you specifically, deliberately need to render markup, and even then, sanitize untrusted content first.
Q88. How do you handle DOM events in a memory-efficient way?
Prefer event delegation (one listener on a parent, covered earlier) over attaching individual listeners to many child elements, and always call removeEventListener for listeners attached to elements that get removed/replaced dynamically — an orphaned listener referencing a removed element (or capturing a closure over other data) is a common, quiet source of memory leaks in long-running single-page apps.
Tooling and Build Systems
Q89. What is npm, and how do you use it?
npm install lodash # add a dependency
npm install --save-dev jest # add a dev-only dependency
npm run build # run a script defined in package.jsonnpm is Node's package manager (and registry) — it installs and manages third-party dependencies (recorded in package.json, pinned in package-lock.json for reproducible installs), and runs project scripts (build, test, lint) defined in the same package.json.
Q90. Discuss the role of Webpack in modern JavaScript development.
Webpack bundles many source files (JS, CSS, images, treated as modules via loaders) into optimized output files for the browser — handling code splitting, minification, and dev-server hot reloading. Vite has become a common faster alternative for many new projects (leveraging native ES modules during development instead of bundling everything upfront), but Webpack remains widely used, especially in existing/larger codebases.
Q91. What is a source map?
A source map maps positions in minified/transpiled/bundled production code back to the original source — so a browser's DevTools (or an error-tracking service) can show you the actual original file/line a bug occurred in, instead of an unreadable line in a single giant minified bundle.
Q92. How do you use ESLint for maintaining JavaScript code quality?
// eslint.config.js
export default [
{ rules: { "no-unused-vars": "warn", eqeqeq: "error" } }
];ESLint statically analyzes code against configurable rules — flagging likely bugs (unused variables, unreachable code), enforcing style consistency, and, integrated into CI, blocking a merge if violations are found — catching a class of mistakes automatically rather than relying on every reviewer to spot them manually.
Q93. What is continuous integration/continuous deployment (CI/CD) in the context of JS development?
CI runs automated checks (lint, tests, build) on every push/PR to catch regressions before merge; CD automates deploying the result once those checks pass — for a JS project this typically means a pipeline running npm ci, npm test, npm run build, then deploying the built static assets/server bundle, all triggered automatically rather than manually run before each release.
JavaScript and the Web Platform
Q94. What is the Window object and its significance?
window is the global object in a browser environment — every global variable/function is technically a property of it, and it also exposes browser-specific APIs (location, history, localStorage, setTimeout) that aren't part of the JS language itself but are ubiquitously available because the browser attaches them here.
Q95. Explain the Document object.
document (a property of window) represents the loaded HTML page itself — the entry point for essentially all DOM manipulation (querySelector, createElement, and the whole DOM tree hang off it).
Q96. What new features does HTML5 bring to JavaScript development?
- Semantic elements (<header>, <article>, <section>) improving accessibility/SEO without extra JS
- Canvas and SVG for programmatic graphics
- Native audio/video elements without a plugin (goodbye Flash)
- Web Storage (localStorage/sessionStorage), Geolocation, and Web Workers as new JS-accessible APIs
Q97. Discuss the role of JavaScript in Progressive Web Apps (PWAs).
A service worker (a JS script running independently of any page, intercepting network requests) is what enables a PWA's offline support and caching strategy, and the Web App Manifest (a JSON file) plus JS-driven install prompts let a web app be added to a home screen and behave much like a native app — JS is the mechanism behind essentially every PWA capability beyond the manifest itself.
JavaScript and Mobile Development
Q98. Explain how to use JavaScript for mobile development.
| Approach | How |
|---|---|
| Responsive web app | A normal website, styled to work well on mobile viewports |
| PWA | A web app with offline support and installability, no app store needed |
| React Native / native bridges | JS driving genuinely native UI components, not a webview |
Q99. What is React Native and how does it differ from traditional web apps?
| Traditional web app | React Native | |
|---|---|---|
| Rendering target | HTML/CSS in a browser engine | Real native UI components (UIView, Android View) |
| Runs where | A browser (or webview) | Directly as a native mobile app, no webview involved |
| Code reuse | Web only | Shares most business logic across iOS and Android |
React Native uses the same React component model, but instead of rendering to the DOM, it renders to actual native platform UI components — the app feels and performs like a native app, not a website wrapped in a webview (which is what earlier "hybrid" frameworks like Cordova/PhoneGap did instead).
Q100. How does JavaScript interact with native mobile components?
In React Native, a JS bridge (or, in newer architecture, JSI — a more direct synchronous binding) passes messages between the JavaScript thread and the native side, letting JS code invoke native modules (camera, GPS, native UI components) and receive native events back — the same underlying idea Web APIs provide in a browser, just for native mobile capabilities instead.
Test yourself
A quick mock test covering the ground above — the rapid-fire round that often opens a JavaScript interview before the deeper follow-ups.
Question 1 of 8
Score: 0 / 0
1. What's the key difference between == and ===?