1. JS Fundamentals & How Code Runs
- JavaScript runs directly inside every web browser without installing any extra software.
- The Google V8 engine compiles JavaScript into high-speed machine code for instant execution.
- Use the `defer` attribute on script tags to download scripts in background without freezing page rendering.
1. What role does JavaScript play in building modern web pages?
Explanation: JavaScript provides the interactivity and dynamic logic for websites.
2. Which engine powers JavaScript execution inside Google Chrome?
Explanation: Google V8 is the open-source high-performance JavaScript engine used in Chrome and Node.js.
3. Which attribute should you add to <script> to download in background and execute cleanly after HTML parses?
Explanation: defer downloads asynchronously and runs in order after HTML parsing completes.
4. Do you need to install any heavy compiler software to run basic JavaScript?
Explanation: All web browsers can run JavaScript natively out of the box.
Answer: Both download scripts in the background without blocking HTML parsing. However, defer guarantees scripts execute in the exact order they appear, and only after HTML parsing is complete. In contrast, async executes immediately the moment it downloads, which can cause bugs if scripts depend on DOM elements not yet rendered.
Answer: In the Browser, JavaScript has access to window objects and web APIs like document (DOM manipulation), localStorage, and fetch, but cannot directly read private computer files. In Node.js, JavaScript runs on a server without a browser window, giving it access to operating system files (fs), network servers (http), and database connections.
Answer: Hoisting is JavaScript's default behavior of moving variable and function declarations to the top of their scope during compilation. Function declarations are fully hoisted with their body, whereas var is hoisted and initialized with undefined, and let/const are hoisted in the Temporal Dead Zone without initialization.
Answer: JavaScript is strictly single-threaded, meaning it executes code line by line on a single main thread with one Call Stack. Asynchronous tasks like timers and network requests are handled non-blockingly by the browser Web APIs and the Event Loop.
2. Variables & Scope (let, const, var)
let for values that change and const for values that stay constant.
const like a car license plate bolted to the bumper (it cannot be replaced), let like a dry-erase whiteboard on your desk that you can rewrite daily, and var like an old megaphone that leaks everywhere!
- Use `const` by default for variables that will not be reassigned.
- Use `let` when the value needs to change over time (like a loop counter or game score).
- Avoid using `var` because it leaks outside of `{ }` code blocks and causes bugs.
1. Which keyword should you use by default when declaring a variable that will NOT be reassigned?
Explanation: const should be your default choice to prevent accidental reassignments and bugs.
2. What is the scope of variables declared with `let` and `const`?
Explanation: let and const are strictly limited to the block { } where they are declared.
3. What happens if you try to reassign a primitive variable declared with `const` (e.g., const x = 5; x = 10)?
Explanation: JavaScript throws a TypeError: Assignment to constant variable.
4. What is the "Temporal Dead Zone" (TDZ) in JavaScript?
Explanation: Accessing a let/const variable in its TDZ throws a ReferenceError.
Answer: 1. Scope: var is function-scoped, whereas let and const are block-scoped (strictly bound inside { }).
2. Reassignment: var and let can be reassigned; const cannot be reassigned.
3. Hoisting: var is hoisted and initialized with undefined. let and const are hoisted into the Temporal Dead Zone (TDZ) and throw a ReferenceError if accessed before declaration.
Answer: Yes! const creates an immutable reference to the memory address, NOT an immutable value. You cannot reassign the variable to a completely new object or array (e.g. arr = []), but you can freely push items, pop items, or modify existing object keys.
Answer: Variable shadowing occurs when a variable declared inside an inner scope (like inside an if block or function) shares the exact same name as a variable in an outer parent scope. The inner variable shadows (hides) the outer variable inside that inner block.
Answer: An undefined variable has been declared using let, const, or var, but has not yet been assigned any value. An undeclared variable has never been declared anywhere; attempting to read it throws a ReferenceError.
3. JavaScript Comments & Best Practices
📚 Core Concept Breakdown
- Single-Line Comments: Begins with two forward slashes
//. Everything from//to the end of that specific line is skipped. - Multi-Line (Block) Comments: Begins with
/*and terminates with*/. Can span multiple lines across complex algorithms. - JSDoc Standard: Professional codebases use
/** ... */with tags like@paramand@returnto generate autocompletion tooltips in VS Code and IDEs. - Good Commenting Rule: Comment on the WHY (business logic and architectural decisions), not the WHAT (obvious syntax). Write clean variable names so code explains itself.
Explanation: In JavaScript, two forward slashes // create a single-line comment. Everything following on that line is ignored by the engine.
Explanation: Multi-line comments start with /* and end with */, allowing comments to span across any number of lines.
Explanation: During lexical analysis (tokenization), the JavaScript engine strips out all comments. They have zero impact on runtime execution logic.
Explanation: JSDoc is the industry standard for documenting JavaScript code. IDEs like VS Code use JSDoc tags (@param, @returns) to provide instant type hints and documentation.
Answer: In modern web development, build tools and bundlers (like Webpack, Vite, esbuild, and Terser) perform "tree shaking" and "minification". During this process, all comments are stripped from JavaScript files to reduce network bundle size, saving bandwidth and boosting page load speed.
Answer: Self-documenting code uses expressive, descriptive variable and function names (e.g. calculateMonthlyMortgagePayment() instead of calc()) that make comments explaining "what" unnecessary. Comments should be reserved for explaining "why" unusual decisions or edge cases exist (e.g., handling a specific safari rendering bug or regulatory tax calculation).
Answer: No! JavaScript does not support nested block comments. The first occurrence of */ will close the entire comment block, causing the remainder of the intended comment to trigger a SyntaxError: Unexpected token.
Answer: In Unix/Linux CLI utilities, a line starting with #!/usr/bin/env node at the very first line of a file instructs the operating system kernel which interpreter to use when executing the file directly from the terminal without typing node script.js. ECMAScript officially standardized hashbang grammar support.
3. Data Types: Primitives & Objects
- Primitives (string, number, boolean, null, undefined) are stored directly by value.
- Objects and arrays are reference types stored in memory heap and copied by memory address.
- Use `typeof` to check the data type of any variable in your code.
1. Which of the following is a primitive data type in JavaScript?
Explanation: boolean is one of the 7 primitive types in JavaScript.
2. What is the historical output of `typeof null` in JavaScript?
Explanation: Due to a legacy 1995 design quirk, typeof null returns "object".
3. If `let a = { score: 10 }; let b = a; b.score = 20;`, what is `a.score`?
Explanation: Objects are reference types; modifying via one variable affects all references.
4. Which memory space stores fast, fixed-size primitive variables?
Explanation: The Call Stack holds primitive values and execution frames for instant access.
Answer: Primitive types (string, number, boolean, null, undefined, symbol, bigint) are stored directly by value in the Call Stack. When copied, a completely independent copy is created.
Reference types (objects, arrays, functions) are stored in the memory Heap. Variables hold a reference (pointer address) to the heap location. Copying the variable merely copies the memory pointer.
Answer: typeof null === "object" is a famous bug from the original 1995 JavaScript implementation where type tags for objects were represented by 0, matching null's null pointer. It cannot be fixed without breaking existing websites. To check if a value is strictly null, use strict comparison: value === null.
Answer: The 7 primitive types are: string, number, boolean, null, undefined, symbol, and bigint. Primitives are immutable and compared by value, whereas Objects are mutable and compared by memory reference.
Answer: This is a famous historical bug from the first release of JavaScript in 1995. Values were marked with type tags where 0 represented an object, and null was implemented as a NULL pointer (0x00). It has been kept for backward compatibility with millions of existing websites.
4. Comparisons & Truthy / Falsy (== vs ===)
===) instead of loose equality (==) to write reliable, predictable programs.
== like a lenient airport guard who accepts a student ID as a passport (loose type conversion), whereas === is a strict border biometric scanner requiring the exact same type and value!
- `===` checks both value and data type without any secret automatic conversion.
- `==` converts types automatically behind your back, frequently causing unexpected bugs.
- The only 6 falsy values in JavaScript are: `false`, `0`, `""`, `null`, `undefined`, and `NaN`.
1. What is the result of `"10" === 10` in JavaScript?
Explanation: Strict comparison === requires both type and value to match.
2. Which of the following values is evaluated as TRUTHY in an if condition?
Explanation: Any non-empty string, even "0" or "false", is truthy in JavaScript!
3. What is the output of `NaN === NaN`?
Explanation: By definition in IEEE 754 and JavaScript, NaN is not equal to anything, including itself.
4. How do you check if a variable `score` is strictly not equal to 100?
Explanation: !== is the strict not-equal operator.
Answer: === (strict equality) compares both value and type without performing implicit type coercion, preventing surprising bugs like 0 == "" (true) or false == "0" (true). === makes your code explicit, predictable, and easier to debug.
Answer: The 6 falsy values in JavaScript are: false, 0 (and -0, 0n), "" (empty string), null, undefined, and NaN. To test if a value is truthy, you can pass it to an if statement or use double-negation: Boolean(val) or !!val.
Answer: undefined means a variable has been declared but not yet assigned any value (system default). null is an intentional assignment by the developer representing an intentional absence of any object value or empty state.
Answer: The falsy values in JavaScript are strictly: false, 0, -0, "" (empty string), null, undefined, NaN, and 0n (BigInt zero). Everything else, including empty arrays [] and empty objects {}, is truthy.
5. Functions & Arrow Functions (=>)
=>) like a compact laser pointer: concise, modern syntax that doesn't drag along its own heavy luggage (this context)!
- Arrow functions `() => {}` provide a cleaner, shorter way to write functions.
- You can give parameters default fallback values in case no argument is passed.
- Arrow functions automatically inherit `this` from their outer surrounding scope.
1. What is the shorthand arrow syntax for a function taking x and returning x multiplied by 2?
Explanation: With single parameters and expressions, parentheses and return are optional in arrow functions.
2. How do arrow functions handle the `this` keyword?
Explanation: Arrow functions do not bind their own this; they use the lexical enclosing context.
3. What value does a function return if it has no `return` statement?
Explanation: In JavaScript, functions without an explicit return statement evaluate to undefined.
4. Can you instantiate an arrow function using the `new` keyword (e.g. new MyArrow())?
Explanation: Attempting to use new with an arrow function throws a TypeError.
Answer: 1. Syntax: Arrow functions provide shorter syntax with implicit returns for single expressions.
2. `this` binding: Arrow functions do not have their own this; they lexically inherit this from the enclosing parent scope.
3. Constructor: Arrow functions cannot be used as constructors with new.
4. `arguments` object: Arrow functions do not have an arguments object; use Rest parameters (...args) instead.
Answer: Default parameters allow initializing named parameters with default values if no value or undefined is passed. Prior to ES6, developers had to write manual checks like name = name || "Default", which failed for valid falsy values like 0 or false.
Answer: Function declarations (function greet() {}) are hoisted entirely to the top of the scope, so they can be invoked before they appear in code. Function expressions (const greet = function() {}) are assigned to variables and cannot be called before definition.
Answer: No. Arrow functions do not possess their own this, arguments, or super bindings. They capture this lexically from their enclosing parent scope, making them ideal for callbacks.
6. Closures & Private State
- Closures allow you to create private variables that cannot be accessed directly from outside.
- They are created automatically every time a function is defined inside another function.
- Using `let` in loops creates a separate closure binding for each loop step.
1. What is a closure in simple terms?
Explanation: Closures preserve their lexical environment.
2. Why are closures helpful for creating private variables?
Explanation: Closures encapsulate state, providing privacy.
3. In `for (let i = 0; i < 3; i++)`, why does each iteration preserve its own value of `i`?
Explanation: ES6 let creates a fresh binding per iteration.
4. Can closures cause memory leaks if not managed carefully?
Explanation: Variables retained in active closures cannot be freed by garbage collection.
Answer: A closure is the combination of a function bundled together with references to its surrounding lexical environment. Practical use cases include:
1. Data privacy / encapsulation: Emulating private variables that cannot be accessed directly from outside.
2. Function factories: Creating customized functions (e.g. multiplyBy(2), multiplyBy(10)).
3. Event handlers & memoization: Caching results and maintaining state across asynchronous calls.
Answer: It logs 3, 3, 3 because var is function-scoped, meaning all three timer callbacks share the exact same variable i after the loop finishes. To fix this, change var to let: for (let i = 0; i < 3; i++). Because let is block-scoped, a fresh i is bound for each iteration, logging 0, 1, 2.
Answer: Closures are used for: 1. Data encapsulation/privacy (creating private variables in functions), 2. Factory functions, 3. Currying and partial application, and 4. Event handlers and timers that retain state.
Answer: Yes. If a closure retains references to large objects, arrays, or DOM elements that are no longer needed, the JavaScript garbage collector cannot reclaim that memory, resulting in memory leaks if listeners are not cleaned up.
7. Arrays & Modern Methods (map, filter, reduce)
map, filter, and reduce let you process lists cleanly without manual for loops.
map like giving every student a medal, filter like selecting only students with height > 5ft for basketball, and reduce like adding up all their test scores into one class average!
- `map()` transforms each item and returns a brand new array of identical length.
- `filter()` creates a new array containing only items that match your condition.
- `reduce()` accumulates all elements into one single final calculated result.
1. Which array method transforms every element and returns a NEW array of identical length?
Explanation: map() applies a transformation function to each item and returns a new array.
2. Does the `filter()` method mutate (change) the original array?
Explanation: filter() is a non-mutating method that produces a new array.
3. Which method should you use to find the first single element in an array matching a condition?
Explanation: find() returns the first element that satisfies the testing function.
4. What is the result of `[1, 2, 3].reduce((acc, curr) => acc + curr, 0)`?
Explanation: 0 + 1 + 2 + 3 = 6.
Answer: forEach() executes a provided function once for each array element and always returns undefined. It is used purely for side-effects (e.g. logging or saving to a database).
map() transforms every element and returns a brand new array containing the transformed values, leaving the original array unchanged.
Answer: reduce((accumulator, current) => ..., initialValue) iterates through an array, accumulating values into a single output. Passing an explicit initialValue prevents runtime TypeError exceptions on empty arrays and guarantees that the accumulator starts with the expected data type.
Answer: map() transforms every element and returns a brand new array of the same length without altering the original. forEach() iterates through items purely for side effects (like logging or updating DOM) and returns undefined.
Answer: slice(start, end) returns a shallow copy of a portion of an array without modifying the original. splice(start, count, ...items) mutates the original array by deleting or inserting items in place.
8. Objects, Destructuring & Spread (...)
...) makes copying easy.
const {milk, bread} = bag) instead of saying bag.milk repeatedly!
- Destructuring syntax `const { name, age } = user;` unpacks properties in one step.
- The spread operator `...` creates a clean shallow copy of an object or merges multiple objects.
- Missing properties in destructuring safely evaluate to `undefined` or a default value.
1. What is the syntax to unpack `name` and `age` from `const person = { name: "Ali", age: 25 }`?
Explanation: Object destructuring uses curly braces matching the object keys.
2. What happens if you destructure a property that does not exist on the object?
Explanation: Accessing non-existent properties safely yields undefined.
3. How do you combine two arrays `[1, 2]` and `[3, 4]` into one using modern ES6?
Explanation: The spread operator expands both arrays cleanly into a new combined array.
4. What does the Rest parameter do in a function definition like `function test(a, ...others)`?
Explanation: Rest collects all remaining arguments into a real array.
Answer: Although both use the three-dot syntax (...), they serve opposite purposes:
1. Spread: Expands an array or object into individual elements/properties (e.g. [...arr1, ...arr2]).
2. Rest: Collects multiple individual values or remaining arguments into a single array (e.g. function log(first, ...rest)).
Answer: It creates a shallow copy. Top-level primitive properties are independently copied, but nested objects or arrays inside are still copied by memory reference. If you modify a nested object in the clone, the original nested object will also be mutated.
Answer: A shallow copy (using {...obj} or Object.assign()) copies only top-level properties; nested objects still share memory references. A deep copy (using structuredClone(obj)) recursively copies all nested levels into independent memory.
Answer: You can extract properties while providing fallback defaults: const { role = "Student" } = user;. If role is undefined on the object, it automatically falls back to "Student".
9. Prototypes & Prototype Chain
- Every object has a prototype link pointing to an ancestor blueprint.
- Putting shared methods on `prototype` saves memory across all created instances.
- The top end of the JavaScript prototype chain is `Object.prototype`, which links to `null`.
1. What is at the very top end of the JavaScript prototype chain?
Explanation: Object.prototype is the root ancestor; its __proto__ points to null, ending the chain.
2. Why is attaching methods to `Constructor.prototype` better than putting them directly in `this` inside the constructor?
Explanation: Prototype methods are shared, whereas defining in this creates a new function copy for every instance.
3. Which method can you use to check if an object possesses a property directly on itself rather than via prototype?
Explanation: hasOwn and hasOwnProperty check for own non-inherited properties.
4. What does the `new` keyword do when calling a constructor function?
Explanation: new performs object creation, prototype linkage, this binding, and returns the instance.
Answer: When accessing a property on an object, JavaScript first looks at the object itself. If not found, it checks the object's prototype (obj.__proto__), then that prototype's prototype, continuing up the chain until reaching Object.prototype, whose prototype is null. If the property is not found anywhere along the chain, undefined is returned.
Answer: prototype is a property on constructor functions (and classes) that defines the shared methods and properties inherited by all instances created with new.__proto__ is the actual reference property on an object instance that points to its constructor's prototype object.
Answer: Object.create(proto) creates a new object with the specified prototype object, establishing a direct prototype link without running any constructor function.
Answer: The root of the chain is Object.prototype. Its own prototype is null (Object.prototype.__proto__ === null), which halts any further property lookups.
10. ES6 Classes & Object-Oriented JS
extends and super().
- Classes are built on top of JavaScript's existing prototypal inheritance system.
- Call `super()` inside a child class constructor before using `this`.
- Private fields are created by prefixing property names with `#` (e.g. `#password`).
1. Which keyword is used to inherit from another class in modern JavaScript?
Explanation: class Child extends Parent sets up class inheritance.
2. What must you call inside a child class constructor before using `this`?
Explanation: super() calls the parent constructor and initializes this.
3. How do you define a truly private field in a modern ES6+ class?
Explanation: Fields like #balance are hard private and enforced by the JavaScript engine.
4. What does the `static` keyword do on a class method?
Explanation: Static methods are called on the class (e.g. Math.max() or User.create()).
Answer: ES6 classes are primarily syntactic sugar over JavaScript's existing prototypal inheritance. Under the hood, methods declared inside a class body are assigned to the class's prototype object, and extends sets up prototype chain delegation between constructor functions.
Answer: In a subclass that extends a parent class, super() invokes the parent class constructor and initializes the parent state. In JavaScript, you must call `super()` before accessing `this` in a derived constructor, or a ReferenceError will be thrown.
Answer: super() invokes the constructor of the parent class. In derived classes, you must call super() before accessing this, otherwise JavaScript throws a ReferenceError.
Answer: Prefixing a property with a hash symbol # (e.g. #balance = 0;) makes it a private class field. It is strictly inaccessible from outside instances, enforcing true encapsulation at language level.
11. The Event Loop, Call Stack & Async Engine
- The Call Stack tracks running functions using Last-In, First-Out (LIFO) order.
- Web APIs handle timers, network requests, and DOM events in the background.
- Microtasks (like Promises) always execute before Macrotasks (like `setTimeout`).
1. Is JavaScript single-threaded or multi-threaded by default in the main execution context?
Explanation: JavaScript has a single main execution thread.
2. What is the primary role of the Event Loop?
Explanation: The Event Loop checks if the stack is clear and transfers tasks from queues to the stack.
3. Which task queue has higher execution priority: Microtasks (Promises) or Macrotasks (setTimeout)?
Explanation: Microtasks are always completely drained before the next macrotask is allowed to run.
4. What error occurs when a function calls itself infinitely without an exit condition?
Explanation: Infinite recursion fills all stack memory, throwing a Stack Overflow error.
Answer: JavaScript has a single-threaded Call Stack that executes one line of code at a time. When asynchronous tasks like setTimeout or fetch occur, the browser handles them via Web APIs in the background. When ready, their callbacks are placed in queues. The Event Loop continuously monitors the Call Stack: the instant the stack is completely empty, it pulls the next callback from the queue and pushes it onto the stack to execute.
Answer: Microtasks (Promises, queueMicrotask, MutationObserver) have higher priority. After every single stack execution, the Event Loop drains the entire Microtask queue before executing the next single Macrotask (setTimeout, setInterval, DOM events).
Answer: Microtasks (Promises, queueMicrotask) have higher priority and run immediately after the current synchronous script finishes, before the browser renders. Macrotasks (setTimeout, setInterval, I/O) run in subsequent tick cycles after the microtask queue is empty.
Answer: Yes. Because JavaScript runs on a single main thread, an infinite or heavy synchronous while-loop monopolizes the Call Stack, preventing the Event Loop from processing user clicks, scroll events, or screen paints.
12. Promises & Asynchronous Code
.then() and .catch() methods.
- A Promise has 3 states: `pending`, `fulfilled` (success), and `rejected` (failure).
- Handle successful values with `.then()` and errors with `.catch()`.
- Use `Promise.all()` to run multiple promises simultaneously in parallel.
1. What are the three possible states of a JavaScript Promise?
Explanation: These are the three official states defined in the ECMAScript Promise specification.
2. Which method is attached to a Promise chain to handle any errors that occur?
Explanation: .catch() captures any rejected promise or thrown error in the chain.
3. What happens in `Promise.all([p1, p2, p3])` if `p2` rejects with an error?
Explanation: Promise.all has fail-fast behavior.
4. Which method runs at the very end of a Promise chain regardless of success or failure?
Explanation: .finally() runs cleanup code whether the promise resolved or rejected.
Answer: Callback Hell (also known as the "Pyramid of Doom") happens when asynchronous callbacks are nested within callbacks, creating unreadable, deeply indented code that is notoriously difficult to debug and handle errors for.
Promises solve this by flattening the structure into a linear, chainable sequence using .then() and centralizing error handling with a single .catch() block.
Answer: Promise.all() fails fast: if any single promise rejects, the entire returned promise immediately rejects with that error.
Promise.allSettled() waits for all promises to finish regardless of outcome and returns an array of objects detailing whether each promise was fulfilled or rejected with its respective value or reason.
Answer: 1. Pending: initial state, neither fulfilled nor rejected.
2. Fulfilled: operation completed successfully.
3. Rejected: operation failed with an error.
Answer: Promise.all() fails fast if ANY promise rejects. Promise.allSettled() waits for ALL promises to complete regardless of whether they resolve or reject, returning an array of outcome objects with statuses.
13. Async / Await & Modern Clean Async
async and await keywords let you write asynchronous code that reads sequentially like normal synchronous code, making it easy to read and maintain.
async/await like standing in an orderly elevator: it lets your code read like a simple top-to-bottom story while secretly running asynchronously in the background!
- An `async` function automatically wraps and returns a Promise.
- `await` pauses execution inside the async function until the promise resolves.
- Wrap `await` statements in standard `try ... catch` blocks for clean error handling.
1. What does a function prefixed with `async` always return?
Explanation: Even if you return a simple number, an async function wraps it in a resolved Promise.
2. Where can the `await` keyword be placed in JavaScript?
Explanation: await is only valid within async functions or top-level in ES modules.
3. How do you handle errors and network rejections with `await`?
Explanation: try ... catch handles rejected promises seamlessly with async/await.
4. Does `await` freeze the entire browser window and user clicks while waiting?
Explanation: The browser continues rendering animations and handling clicks smoothly.
Answer: 1. Readability: It avoids chaining and allows asynchronous code to look and feel like synchronous code.
2. Error Handling: Enables using standard try / catch blocks for both synchronous and asynchronous errors.
3. Debugging: Step-through debugging in browser DevTools works line-by-line much more smoothly with await than jumping inside callback closures.
Answer: A common mistake is awaiting them sequentially (e.g. const a = await getA(); const b = await getB();). If they are independent, combine them with Promise.all(): const [a, b] = await Promise.all([getA(), getB()]);. This fires both requests in parallel, cutting total wait time in half.
Answer: Wrap the awaited asynchronous operations inside standard try { ... } catch (error) { ... } blocks, or chain a .catch() handler to the promise returned by the async function.
Answer: Yes, in modern ES modules (ES2022+), Top-Level Await allows you to use await directly at the root level of a module file without wrapping it in an async function.
14. DOM Manipulation & Finding Elements
- Use `document.querySelector()` to find elements using standard CSS selectors.
- Always use `element.textContent` instead of `innerHTML` to prevent security vulnerabilities.
- Use `element.classList.add()`, `.remove()`, and `.toggle()` to manage CSS classes.
1. Which method selects the FIRST element matching a CSS selector like `#submit-btn`?
Explanation: querySelector returns the first matching element node.
2. What is the safest property to update element text without exposing your website to XSS attacks?
Explanation: textContent treats all input as plain text, eliminating script injection risks.
3. Which method toggles a CSS class on an element (adding if missing, removing if present)?
Explanation: classList.toggle() cleanly toggles the class state.
4. Which method attaches a newly created element into a parent element on the page?
Explanation: appendChild and append insert nodes into the DOM tree.
Answer: textContent sets or retrieves plain text only. It parses everything as raw strings, making it completely safe against Cross-Site Scripting (XSS) attacks.
innerHTML parses the string as actual HTML markup. If you insert user-submitted text using innerHTML, an attacker can inject malicious <script> or <img onerror="..."> tags to steal user passwords or tokens.
Answer: Reflow (Layout) happens when changes affect the geometry/dimensions of elements (e.g. width, height, adding nodes), requiring the browser to recalculate element positions.
Repaint happens when changes affect visual styling without changing geometry (e.g. background color, visibility).
To minimize them, batch DOM changes using DocumentFragment, animate using CSS transform and opacity (which run on the GPU), and avoid reading layout properties repeatedly in loops.
Answer: getElementById only finds an element by its ID attribute and is slightly faster. querySelector accepts any valid CSS selector (classes, IDs, attributes, pseudo-classes) and returns the first matching element.
Answer: textContent returns or sets only raw text and is secure against XSS injection attacks. innerHTML parses HTML markup strings, creating HTML nodes but opening security risks if used with untrusted input.
15. DOM Events, Bubbling & Delegation
- Use `element.addEventListener("click", handler)` to listen for user interactions cleanly.
- Stop event bubbling when needed by calling `event.stopPropagation()`.
- Event Delegation attaches one listener to a parent element to manage clicks on many child items.
1. What direction does Event Bubbling travel in the DOM tree?
Explanation: Bubbling travels upwards from the target to the root document.
2. Which method stops an event from continuing to bubble up to parent elements?
Explanation: stopPropagation() halts the bubbling chain at the current element.
3. What does `event.preventDefault()` do on a form submit button click?
Explanation: It stops default browser actions like form submissions or following links.
4. In Event Delegation, why is attaching one listener to a parent list better than 500 listeners on list items?
Explanation: Event delegation provides significant performance gains and handles dynamic items.
Answer: Event Delegation is a pattern where you attach a single event listener to a common parent element rather than attaching individual listeners to multiple child elements. It leverages Event Bubbling. Benefits include:
1. Memory efficiency: One event listener uses far less RAM than hundreds of listeners.
2. Dynamic elements: Newly added child elements automatically work without needing new listeners.
Answer: event.target is the actual innermost element that originated the event (e.g. the specific icon or button that was clicked).
event.currentTarget is the element to which the event listener is currently attached (the element handling the event in the bubbling chain).
Answer: Event Delegation is attaching a single event listener to a common parent element rather than attaching separate listeners to many child elements, using event.target to detect clicks. This saves memory and automatically handles dynamic elements.
Answer: preventDefault() stops the default browser action (like following a link or submitting a form). stopPropagation() prevents the event from bubbling up the DOM tree to ancestor elements.
16. Browser Storage (LocalStorage & SessionStorage)
localStorage like a permanent refrigerator magnet notepad (persists after closing the browser), and sessionStorage like a hotel room safe that wipes clean when you check out!
- `localStorage` keeps data permanently until explicitly cleared by code or user.
- `sessionStorage` deletes its stored data as soon as the browser tab is closed.
- Web Storage only stores strings; convert objects using `JSON.stringify()` and `JSON.parse()`.
1. When does data stored in `localStorage` expire by default?
Explanation: localStorage has no built-in expiration time.
2. What format must data be converted into when saving arrays or objects in `localStorage`?
Explanation: localStorage only accepts string keys and values.
3. How do you retrieve a saved item named "theme" from localStorage?
Explanation: getItem() retrieves values by key name.
4. What is the storage capacity limit for `localStorage` per website domain?
Explanation: Most modern browsers allow ~5MB to 10MB of storage per origin.
Answer: 1. Capacity: localStorage and sessionStorage provide ~5MB-10MB per origin, while cookies only hold ~4KB.
2. Lifecycle: localStorage persists until explicitly cleared. sessionStorage is cleared when the tab closes. Cookies persist until their expiration date.
3. Server Communication: Cookies are sent automatically with every HTTP request header (increasing network payload), whereas Web Storage stays strictly local on the client.
Answer: localStorage is accessible to any JavaScript running on your page. If your site has a single Cross-Site Scripting (XSS) vulnerability, an attacker can execute localStorage.getItem("token") and steal authentication credentials. Sensitive tokens are much safer stored in HttpOnly, Secure cookies, which cannot be read by JavaScript.
Answer: localStorage provides approximately 5MB - 10MB per origin, stored purely in the browser. Traditional HTTP cookies are limited to only 4KB and are sent over the network with every HTTP request.
Answer: No, localStorage only stores strings. You must serialize objects using JSON.stringify(data) before storing, and deserialize using JSON.parse(string) when retrieving.
17. Fetch API & Connecting to REST APIs
fetch() like sending a courier pigeon to a distant cloud server to fetch the current weather report and deliver it back to your phone!
- `fetch()` returns a Promise that resolves to a `Response` object.
- Check `if (!response.ok)` to detect HTTP errors like 404 Not Found.
- Call `await response.json()` to parse the incoming server response into a JavaScript object.
1. Does `fetch()` reject its Promise when a server returns a 404 Not Found status code?
Explanation: fetch only rejects on actual network failure, not HTTP error codes.
2. Which HTTP method is typically used to request and read data from an API without modifying it?
Explanation: GET is the standard HTTP method for retrieving data.
3. Which HTTP header tells the server that you are sending a JSON formatted body payload in a POST request?
Explanation: Content-Type informs the server how to parse the request body.
4. Which method on the `Response` object parses an incoming JSON stream into a JavaScript object?
Explanation: response.json() reads the body stream to completion and parses it as JSON.
Answer: fetch() only rejects a promise when a network failure occurs (e.g. user is offline, DNS lookup fails, or server is unreachable). An HTTP 404 or 500 is considered a successfully completed HTTP communication from the browser's perspective. To handle HTTP errors, you must explicitly check if (!response.ok) and throw an error manually.
Answer: CORS is a browser security mechanism that blocks web pages on one domain (e.g. app.com) from making HTTP requests to another domain (e.g. api.com) unless the server explicitly sends back the HTTP header Access-Control-Allow-Origin: *. It protects users from malicious sites stealing data from authenticated sessions.
Answer: No! fetch() only rejects if there is a network failure or DNS error. For HTTP 404 or 500 errors, the promise resolves successfully, and you must check response.ok (status 200-299) manually.
Answer: Pass an options object specifying method: "POST", headers: { "Content-Type": "application/json" }, and body: JSON.stringify(data).
18. ES6 Modules: import & export
export the lawnmower you built and import their pressure washer!
- A file can have multiple named exports `export const func = ...` imported with `{ func }`.
- A file can have only one `default` export imported without curly braces.
- ES6 modules execute in strict mode by default and have their own private file scope.
1. How many `default` exports can a single JavaScript module file have?
Explanation: A module can only specify a single default export.
2. How do you import named exports `add` and `sub` from `./math.js`?
Explanation: Named exports are unpacked using curly braces.
3. Do ES6 modules automatically execute in Strict Mode ("use strict")?
Explanation: All ES modules run in strict mode automatically without needing "use strict".
4. Which attribute must you add to an HTML <script> tag to enable ES6 module imports?
Explanation: Adding type="module" to the script tag enables modern ES6 module imports in browsers.
Answer: Named Exports: A file can have multiple named exports. When importing, consumers must use matching curly braces (e.g. import { a, b } from "./utils.js") unless renamed with as.
Default Export: A file can have only ONE default export (export default ...). When importing, no curly braces are used, and the importing file can assign any custom identifier name.
Answer: Tree Shaking is a build-time dead-code elimination optimization used by modern bundlers (like Vite, Webpack, Rollup). Because ES6 import and export statements are static (they cannot be conditionally loaded inside if-statements), bundlers can analyze the exact abstract syntax tree and exclude all unused functions from the final production bundle, drastically shrinking file size.
Answer: A file can have only one default export (imported without braces: import math from './math.js'). A file can have multiple named exports (imported with exact names in braces: import { add, sub } from './math.js').
<script type="module"> in HTML?
▼
Answer: Adding type="module" instructs the browser to treat the script as an ES module, enabling import/export statements, running automatically in strict mode, and deferring execution until HTML is parsed.
19. Error Handling & Debugging Techniques
try, catch, and finally allows your code to handle problems gracefully without crashing the whole application.
- Code inside `try { ... }` runs, and any thrown error is caught in `catch (err) { ... }`.
- The `finally` block runs in all situations, making it ideal for cleanup operations.
- Use `console.table()` to view arrays of objects as structured tables in browser DevTools.
1. When does the `finally` block in a `try...catch...finally` construct execute?
Explanation: finally is guaranteed to execute for cleanup tasks.
2. How do you create and trigger a custom error message in JavaScript?
Explanation: throw new Error(...) instantiates and throws a standard error.
3. Which console method formats an array of objects into a clean, readable table in DevTools?
Explanation: console.table() presents tabular data with sortable columns in DevTools.
4. What happens when code reaches a `debugger;` statement while Chrome DevTools is open?
Explanation: debugger acts as an active breakpoint.
Answer: The finally block executes unconditionally: whether the try block succeeds or throws an error caught by catch. It even executes if the try or catch block contains a return statement, making it the ideal place for cleanup operations (closing file handles, stopping loading spinners).
Answer: The debugger; statement acts as a programmatic breakpoint. If browser Developer Tools are open, execution immediately pauses at that line, allowing developers to inspect current scope variables, the call stack, and step over/into subsequent instructions line-by-line.
Answer: The finally block executes unconditionally regardless of whether an error was thrown or handled in the try/catch blocks. It is typically used for cleanup like closing files or resetting loading spinners.
Answer: A class that extends the built-in Error class (e.g. class ValidationError extends Error {}), allowing you to define domain-specific error types with custom status codes or messages.
20. Performance Optimization: Debounce & Clean Code
- Debouncing delays execution until a user has paused typing for a set time limit.
- Throttling limits function execution to at most once per fixed time interval.
- Clean up timers with `clearInterval()` to prevent memory leaks and wasted CPU cycles.
1. Which technique waits until a user has paused typing for a specified delay before calling a search API?
Explanation: Debouncing resets its timer on every keystroke and only fires after a quiet pause.
2. Which technique limits a scroll event handler to run at most once every 100 milliseconds?
Explanation: Throttling enforces a maximum frequency rate of execution.
3. What common problem happens if you create an interval with `setInterval()` and never clear it?
Explanation: The timer closure continues running and retaining memory indefinitely.
4. What is a "Pure Function" in clean coding best practices?
Explanation: Pure functions are predictable, bug-free, and easy to unit test.
Answer: Debounce: Delays execution until a certain amount of time has passed since the last event was triggered. Best for search inputs, window resize, and auto-saving drafts.
Throttle: Limits execution to at most once per fixed time interval regardless of how frequently events fire. Best for continuous events like page scrolling, drag-and-drop, and game loop updates.
Answer: 1. Uncleared timers: Forgetting to call clearInterval() or clearTimeout().
2. Dangling event listeners: Leaving listeners attached to detached DOM nodes.
3. Accidental global variables: Forgetting const/let keywords.
4. Closures holding large objects: Unintentionally retaining references to large arrays in long-lived closures.
Answer: Debouncing delays function execution until after a specified pause in events (ideal for search autocomplete). Throttling limits function execution to at most once per fixed time interval (ideal for scroll or window resize handlers).
Answer: Tree-shaking is dead-code elimination performed by bundlers like Vite and Webpack, removing unused export statements from the final bundle to reduce file size.
21. The 'this' Keyword & Function Binding
this keyword refers to the object currently executing the function. You can easily control what this points to using call(), apply(), and bind().
this like the pronoun "I" in conversation: who "I" refers to depends entirely on who is holding the microphone and speaking right now!
- Object Method: When a function is called as an object method (
user.sayHi()),thispoints touser. - call() & apply(): Immediately runs a function with a custom
thisobject.calltakes arguments comma-separated;applytakes an array. - bind(): Creates and returns a brand-new function with
thispermanently locked to an object for later use.
1. In an object method like person.getName(), what does 'this' point to?
Explanation: When a method is called on an object,
this naturally refers to that object.
2. What is the difference between call() and apply()?
Explanation: Remember: Apply takes an Array of arguments!
3. What does the bind() method do?
Explanation:
bind() creates a new reusable function with its context permanently set.
4. How do Arrow Functions handle 'this'?
Explanation: Arrow functions use lexical scoping for
this, making callbacks much cleaner!
Answer: this is a special keyword that references the object that called the current function. Its value depends on how and where the function is executed.
Answer: You use call() or apply() when you want to borrow a method from one object and run it on another object immediately without copying code.
Answer: Because callbacks in timers and event listeners often lose their original object context. bind() locks this to the right object so the callback behaves properly.
Answer: Arrow functions do not bind their own this; they automatically inherit it from the surrounding code, avoiding the need for .bind(this) or const self = this.