Top JavaScript Interview Questions

    1

    What are the different data types in JavaScript?

    JavaScript has two main categories of data types:

    • Primitive Types: Immutable values stored directly in the location the variable accesses.
      • String: Textual data.
      • Number: Numeric values (including Infinity and NaN).
      • Boolean: true or false.
      • null: Represents the intentional absence of any object value.
      • undefined: A variable that has been declared but not yet assigned a value.
      • Symbol (ES6): A unique and immutable primitive.
      • BigInt (ES2020): Represents integers with arbitrary precision.
    • Reference Type:
      • Object: A collection of key-value pairs. Arrays, functions, and other complex structures are objects.
    2

    What is the difference between `==` and `===`?

    • == (Loose Equality): Compares two values for equality after performing type coercion. This can lead to unexpected results.
    • === (Strict Equality): Compares two values for equality without type coercion. It checks if both the value and the type are the same.
    Expression=====Reason for Loose Equality
    5 == "5"truefalseString "5" is coerced to Number 5.
    0 == falsetruefalsefalse is coerced to Number 0.
    null == undefinedtruefalseThis is a specific rule in the spec.

    Best Practice: Always use === to prevent bugs from unintended type conversions.

    3

    Explain the difference between `null` and `undefined`.

    Featureundefinednull
    TypeIts type is undefined.Its type is object (a historical bug).
    MeaningRepresents the absence of a value due to the system (e.g., unassigned variable, missing object property).Represents the intentional absence of a value, explicitly set by the programmer.
    Examplelet x; console.log(x); // undefinedlet x = null; console.log(x); // null
    4

    What is the concept of "truthy" and "falsy" values?

    In a boolean context (like an if statement), every value in JavaScript behaves as either true or false.

    • Falsy values are values that are coerced to false. There are only eight:
      1. false
      2. 0 (zero)
      3. -0 (minus zero)
      4. 0n (BigInt zero)
      5. "" (empty string)
      6. null
      7. undefined
      8. NaN (Not a Number)
    • Truthy values are all other values, including {}, [], "0", "false", and functions.
    5

    What is `NaN` and how can you check for it?

    NaN stands for "Not a Number". It's a special numeric value that represents an invalid or unrepresentable number, often the result of a failed mathematical operation. A unique property of NaN is that it is not equal to anything, including itself (NaN === NaN is false). Therefore, you cannot check for it with equality operators. Use Number.isNaN() instead.

    console.log(NaN === NaN); // false console.log(Number.isNaN(NaN)); // true console.log(Number.isNaN(1 / 'a')); // true
    6

    What is the difference between `let`, `const`, and `var`?

    Featurevarletconst
    ScopeFunction-scopedBlock-scoped ({})Block-scoped ({})
    HoistingHoisted and initialized to undefinedHoisted but not initialized (TDZ)Hoisted but not initialized (TDZ)
    ReassignmentCan be reassignedCan be reassignedCannot be reassigned
    RedeclarationCan be redeclared in same scopeCannot be redeclared in same scopeCannot be redeclared in same scope
    7

    What is the Temporal Dead Zone (TDZ)?

    The Temporal Dead Zone is a behavior in ES6 that occurs when accessing a let or const variable before its declaration. The period from the start of the block until the declaration is processed is the TDZ for that variable. Accessing the variable in the TDZ results in a ReferenceError.

    8

    What is the `typeof` operator and what are some common gotchas?

    The typeof operator returns a string indicating the type of the unevaluated operand. Gotchas:

    • typeof null returns "object". This is a long-standing bug.
    • typeof [] returns "object". Arrays are objects.
    • typeof function(){} returns "function". Functions are first-class objects, but have their own type.
    9

    What are wrapper objects for primitives?

    JavaScript provides wrapper objects (String, Number, Boolean) that allow you to call methods on primitive values. When you call a method like .toUpperCase() on a string primitive, JavaScript temporarily wraps it in a String object to access the method, and then discards the wrapper. This is called "autoboxing".

    10

    What does "use strict" do?

    "use strict"; is a directive that enables "strict mode". Strict mode changes certain previously accepted "bad syntax" into real errors, provides more visibility into potential issues, and disables features that are confusing or poorly thought out. For example, in strict mode, assigning a value to an undeclared variable throws an error, and this is undefined in global functions.

    11

    What is type coercion?

    Type coercion is the automatic or implicit conversion of values from one data type to another. This happens in operations like the loose equality == check or when using the + operator with a string and a number.

    12

    What is the global object?

    The global object is an object that always exists in the global scope. In a web browser, it's the window object. In Node.js, it's global. In modern environments, globalThis can be used to access the global object regardless of the context.

    13

    What is the difference between an expression and a statement?

    • Statement: A piece of code that performs an action. Examples: let x = 5;, if (x > 0) { ... }.
    • Expression: A piece of code that evaluates to a value. Examples: 5, x + 10, myFunction(). Every expression can be written as a statement, but not every statement can be an expression.
    14

    What are short-circuiting operators?

    Logical operators && (AND) and || (OR) are short-circuiting.

    • expr1 && expr2: If expr1 is falsy, it returns expr1 without evaluating expr2.
    • expr1 || expr2: If expr1 is truthy, it returns expr1 without evaluating expr2. This is often used for conditional logic or setting default values.
    15

    What does the `instanceof` operator do?

    The instanceof operator checks if an object's prototype chain contains the prototype property of a constructor. It's used to determine if an object is an instance of a particular class or constructor function.


    16

    What is hoisting?

    Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope (function scope for var, block scope for let/const).

    • var variables are hoisted and initialized with undefined.
    • let and const are hoisted but not initialized (creating the TDZ).
    • Function declarations (function foo() {}) are fully hoisted, meaning you can call them before they appear in the code.
    • Function expressions (const foo = function() {}) are not hoisted.
    17

    Explain lexical scoping.

    Lexical scoping (or static scoping) means that the accessibility of variables is determined by the position of the variables and blocks of code at the time of writing. An inner function has access to the scope of its parent functions, regardless of where the function is executed. This is what makes closures possible.

    18

    What is a closure?

    A closure is a function that remembers the environment in which it was created. It's the combination of a function and the lexical environment within which that function was declared. This means an inner function has access to its outer function's variables and parameters, even after the outer function has returned.

    function createCounter() { let count = 0; return function() { count++; console.log(count); }; } const counter = createCounter(); counter(); // 1 counter(); // 2
    19

    What is the `this` keyword?

    The value of this is determined by how a function is called (its "call site").

    • Global Context: this refers to the global object (window in browsers).
    • Function Call: this is the global object in non-strict mode, undefined in strict mode.
    • Method Call (obj.myMethod()): this is the object the method was called on (obj).
    • Constructor Call (new MyClass()): this is the newly created instance.
    • Arrow Functions: this is lexically bound; it inherits this from the parent scope.
    20

    Explain `call()`, `apply()`, and `bind()`.

    These methods are used to set the this value of a function explicitly.

    • call(thisArg, arg1, arg2, ...): Invokes the function immediately with a given this value and arguments provided individually.
    • apply(thisArg, [argsArray]): Invokes the function immediately with a given this value and an array of arguments.
    • bind(thisArg): Returns a new function with this permanently bound to thisArg. It does not invoke the function immediately.
    21

    What is a higher-order function?

    A higher-order function is a function that either takes another function as an argument, or returns a function, or both. Array methods like map, filter, and reduce are common examples.

    22

    What is an IIFE (Immediately Invoked Function Expression)?

    An IIFE is a function that is executed right after it is created. It's a common pattern for creating a local scope to avoid polluting the global namespace.

    (function() { var privateVar = "I am private"; // ... })();
    23

    What is the difference between function declarations and function expressions?

    • Function Declaration: function foo() {}. It's a statement, and it's hoisted completely.
    • Function Expression: const foo = function() {}. It's an expression that produces a value (the function). The variable (foo) is hoisted according to its keyword (var, let, const), but the function body is not.
    24

    What are pure functions?

    A pure function is a function that:

    1. Given the same input, will always return the same output.
    2. Has no side effects (e.g., does not modify external state, log to the console, or make network requests). Pure functions are fundamental to functional programming and make code more predictable and testable.
    25

    What is function composition?

    Function composition is the process of combining two or more functions to produce a new function. The output of one function becomes the input of the next.

    const compose = (f, g) => (x) => f(g(x)); const toUpperCase = (str) => str.toUpperCase(); const exclaim = (str) => `${str}!`; const shout = compose(exclaim, toUpperCase); console.log(shout("hello")); // "HELLO!"
    26

    What are default parameters?

    Default parameters (ES6) allow you to initialize named parameters with default values if no value or undefined is passed.

    function greet(name = "Guest") { console.log(`Hello, ${name}`); } greet(); // "Hello, Guest"
    27

    What are rest and spread operators?

    • Rest Operator (...): Collects multiple elements into a single array. It must be the last parameter in a function definition.
      function sum(...numbers) { return numbers.reduce((acc, curr) => acc + curr, 0); }
    • Spread Operator (...): Expands an iterable (like an array or string) into individual elements. Used in function calls, array literals, or object literals.
      const arr = [1, 2, 3]; console.log(Math.max(...arr)); // 3
    28

    What is a generator function?

    A generator function (function*) can be paused and resumed, allowing it to produce a sequence of values over time. It uses the yield keyword to produce a value. It returns a generator object, which is an iterator.

    29

    What is recursion?

    Recursion is a technique where a function calls itself to solve a problem. A recursive function must have a base case to stop the recursion and a recursive step that moves it closer to the base case.

    30

    What is a callback function?

    A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. It's the cornerstone of asynchronous programming in JavaScript.


    31

    Explain prototypal inheritance.

    JavaScript uses prototypal inheritance. Every object has a hidden [[Prototype]] property that is either null or references another object (its "prototype"). When you try to access a property on an object, if it's not found on the object itself, the JavaScript engine searches the object's prototype, then that prototype's prototype, and so on, until the property is found or the end of the chain (null) is reached. This is called the prototype chain.

    32

    What is the `prototype` property on a function?

    Every regular function (not arrow functions) has a prototype property. This property is an object that will become the prototype of any new object instances created by that function when used as a constructor with the new keyword.

    33

    `__proto__` vs. `prototype`

    • prototype: A property on a constructor function that defines the prototype for its instances.
    • __proto__: A property on an object instance that points to its prototype. It's a getter/setter for the internal [[Prototype]] property. Object.getPrototypeOf() is the standard way to access it.
    34

    How do you create objects in JavaScript?

    1. Object Literal: const obj = { key: 'value' };
    2. Constructor Function: function Person(name) { this.name = name; } const p = new Person('Al');
    3. ES6 Class: class Person { ... } const p = new Person('Al');
    4. Object.create(): const obj = Object.create(somePrototype); Creates a new object with the specified prototype object.
    35

    What does the `new` keyword do?

    The new keyword does four things:

    1. Creates a new, empty plain JavaScript object.
    2. Sets the new object's [[Prototype]] to be the prototype of the constructor function.
    3. Binds this to the newly created object and executes the constructor function's code.
    4. Returns the new object (or the object returned by the constructor if it returns an object).
    36

    What is a constructor function?

    A constructor function is a regular function used to create and initialize objects with the new keyword. By convention, their names start with a capital letter.

    37

    How can you check if an object has a specific property?

    • 'prop' in obj: Returns true if the property exists anywhere in the object's prototype chain.
    • obj.hasOwnProperty('prop'): Returns true only if the property exists directly on the object itself (not on its prototype).
    38

    How do you prevent an object from being modified?

    • Object.freeze(obj): Prevents adding, deleting, or changing properties. The most restrictive.
    • Object.seal(obj): Prevents adding or deleting properties, but allows changing existing ones.
    • Object.preventExtensions(obj): Prevents adding new properties, but allows deleting or changing existing ones.
    39

    What are property descriptors?

    Every property on an object has a property descriptor that defines its characteristics. The main keys are:

    • value: The value of the property.
    • writable: true if the property's value can be changed.
    • enumerable: true if the property will be listed in a for...in loop.
    • configurable: true if the property can be deleted or its descriptor can be changed. You can get a descriptor with Object.getOwnPropertyDescriptor().
    40

    What is the difference between a "deep copy" and a "shallow copy"?

    • Shallow Copy: Copies only the top-level properties. If a property is a reference to another object, only the reference is copied, not the object itself. Both the original and the copy will point to the same nested object. (Object.assign() and the spread operator ... do shallow copies).
    • Deep Copy: Copies all properties and their nested objects recursively, creating a completely independent clone. This requires custom code or a library function (like _.cloneDeep from Lodash). A common but limited hack is JSON.parse(JSON.stringify(obj)), which doesn't work for functions, undefined, or circular references.
    41

    What are getters and setters?

    Getters and setters are special methods that provide read and write access to an object's property. They allow you to run code when a property is accessed or modified.

    const user = { _name: "John", get name() { return this._name; }, set name(value) { if (value.length > 2) this._name = value; } };
    42

    How does `Object.create()` work?

    Object.create(proto) creates a new object and sets its [[Prototype]] to the proto object. This is a direct way to implement prototypal inheritance.

    43

    What is the `Map` object? How is it different from a plain `Object`?

    Map is a collection of key-value pairs where any value (both objects and primitive values) may be used as a key. Differences from Object:

    • Key Types: Map keys can be any type, including objects. Object keys must be strings or symbols.
    • Order: Map remembers the original insertion order of the keys.
    • Size: Map has a .size property.
    • Performance: Map is optimized for frequent additions and removals.
    44

    What is the `Set` object?

    A Set is a collection of unique values. You can store any type of value, but each value can only appear once.

    45

    What is the `WeakMap` object?

    A WeakMap is a Map where the keys must be objects, and the references to the keys are held "weakly". This means that if there are no other references to a key object, it can be garbage collected. This is useful for associating data with an object without preventing it from being collected.


    46

    What is destructuring assignment?

    Destructuring is a syntax that allows you to "unpack" values from arrays or properties from objects into distinct variables.

    // Object destructuring const { name, age } = { name: 'John', age: 34 }; // Array destructuring const [first, second] = [10, 20];
    47

    What are template literals?

    Template literals are strings enclosed in backticks (`) that allow for:

    1. String Interpolation: Embedding expressions directly in the string with ${expression}.
    2. Multi-line Strings: Creating strings that span multiple lines without needing \n.
    48

    What are arrow functions and their main characteristics?

    Arrow functions provide a more concise syntax for writing functions. Key Characteristics:

    1. Concise Syntax: (a, b) => a + b;
    2. Lexical this: They do not have their own this. They inherit this from the surrounding lexical scope.
    3. No arguments object: Use rest parameters (...args) instead.
    4. Cannot be used as constructors: They cannot be called with new.
    49

    What are JavaScript Modules (ESM)?

    ES Modules provide a standardized module system for JavaScript.

    • export: Used to export functions, objects, or primitives from a module.
    • import: Used to import live, read-only bindings to exports from another module. Modules help organize code, avoid polluting the global namespace, and manage dependencies.
    50

    What is a `Promise`?

    A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. A Promise exists in one of three states: pending, fulfilled, or rejected.

    51

    Explain `Promise.all`, `Promise.race`, and `Promise.allSettled`.

    • Promise.all(iterable): Fulfills when all of the promises in the iterable have fulfilled, or rejects as soon as one of them rejects.
    • Promise.race(iterable): Fulfills or rejects as soon as one of the promises in the iterable fulfills or rejects.
    • Promise.allSettled(iterable): Fulfills after all of the given promises have either fulfilled or rejected. The result is an array of objects describing the outcome of each promise. Useful when you need to know the result of every promise, regardless of its status.
    52

    What is `async/await`?

    async/await is syntactic sugar built on top of Promises that makes asynchronous code look and feel more synchronous.

    • async keyword: Placed before a function, it makes the function return a Promise.
    • await keyword: Used inside an async function, it pauses the function execution and waits for a Promise to resolve.
    53

    What are Classes in ES6?

    ES6 classes are syntactic sugar over JavaScript's existing prototype-based inheritance. They provide a much simpler and clearer syntax for creating objects and dealing with inheritance.

    54

    What is the `super` keyword used for in classes?

    The super keyword is used to call methods on an object's parent.

    • In a constructor, super() calls the parent class's constructor.
    • In a method, super.myMethod() calls the parent's version of that method.
    55

    What are Symbols?

    A Symbol is a unique and immutable primitive data type introduced in ES6. They are often used as unique property keys for objects to avoid naming collisions.

    56

    What are iterators and iterables?

    • Iterable: An object that implements the iterable protocol. It must have a [Symbol.iterator] property which is a function that returns an iterator. Examples: Array, String, Map, Set.
    • Iterator: An object that implements the iterator protocol. It must have a next() method that returns an object with two properties: value (the next value in the sequence) and done (a boolean that's true if the sequence is finished).
    57

    What is optional chaining (`?.`)?

    Optional chaining is a safe way to access nested object properties. It stops the evaluation and returns undefined if a reference in the chain is null or undefined. This prevents TypeError exceptions.

    const street = user?.address?.street;
    58

    What is the nullish coalescing operator (`??`)?

    The nullish coalescing operator returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. It's a way to provide a default value for a variable that might be nullish.

    59

    What is the difference between `for...in` and `for...of`?

    • for...in: Iterates over the enumerable property keys of an object, including inherited properties.
    • for...of: Iterates over the values of an iterable object (Array, String, Map, etc.). It does not work on plain objects because they are not iterable by default.
    60

    What are tagged templates?

    Tagged templates are an advanced form of template literals. They allow you to parse template literals with a function. The first argument to the tag function is an array of the string literals, and the subsequent arguments are the evaluated expressions.


    61

    What is the event loop?

    The event loop is the core mechanism in JavaScript that enables non-blocking asynchronous behavior. It's a constantly running process that monitors both the Call Stack and the Callback Queue. If the Call Stack is empty, it takes the first event from the queue and pushes it to the Call Stack, which effectively runs it.

    Call Stack main() Web APIs Callback Queue setTimeout() Callback Event Loop
    62

    What is "callback hell"?

    Callback hell (or the pyramid of doom) is a situation in asynchronous code where multiple nested callbacks make the code hard to read, maintain, and debug. Promises and async/await were created to solve this problem.

    63

    How do you handle errors in `async/await`?

    You use a standard try...catch block, just like with synchronous code.

    async function fetchData() { try { const response = await fetch('invalid-url'); const data = await response.json(); console.log(data); } catch (error) { console.error("Failed to fetch data:", error); } }
    64

    What is the difference between the microtask queue and the macrotask queue?

    The event loop actually has two kinds of queues:

    • Macrotask Queue (or Task Queue): For tasks like setTimeout, setInterval, I/O operations.
    • Microtask Queue: For tasks like Promise callbacks (.then, .catch, .finally) and queueMicrotask. Execution Order: The event loop executes tasks in a specific order. After each macrotask from the macrotask queue is completed, the event loop processes all available tasks in the microtask queue before moving on to the next macrotask. This means microtasks have a higher priority.
    65

    What is the difference between `setTimeout(fn, 0)` and `Promise.resolve().then(fn)`?

    • setTimeout(fn, 0) places the function fn in the macrotask queue.
    • Promise.resolve().then(fn) places fn in the microtask queue. Therefore, the promise callback will always execute before the setTimeout callback if both are scheduled at the same time.
    66

    How does `fetch()` work?

    The fetch() API provides a modern, Promise-based interface for making network requests. It's a Web API, meaning the browser provides it. When you call fetch, the request is sent off in the background. The fetch function immediately returns a Promise that resolves to a Response object once the server has responded with headers. You then need to call another method on the Response object (like .json() or .text()) to read the body of the response, which also returns a promise.

    67

    What is CORS (Cross-Origin Resource Sharing)?

    CORS is a security mechanism implemented by browsers that controls how web pages in one domain can request resources from another domain. The server at the other domain must include specific CORS headers (like Access-Control-Allow-Origin) in its response to permit the cross-origin request.

    68

    What are `AbortController` and `AbortSignal`?

    These are APIs used to abort asynchronous operations, most commonly fetch requests. You create an AbortController, pass its signal property to the fetch options, and then you can call controller.abort() at any time to cancel the request.

    69

    What is JSONP and why is it no longer used?

    JSONP (JSON with Padding) was a hack to get around the same-origin policy before CORS existed. It works by dynamically creating a <script> tag that points to the remote server. The server would wrap the JSON data in a function call. It's no longer used because it's insecure (can lead to XSS) and CORS is the standard, more flexible solution.

    70

    What is long polling?

    Long polling is a technique where the client makes a request to the server, and the server holds the connection open until it has new data to send. Once the data is sent, the connection is closed, and the client immediately opens a new one. It's a way to simulate a server push.

    71

    What are WebSockets?

    WebSockets provide a full-duplex, persistent communication channel between a client and a server over a single TCP connection. This allows for real-time, low-latency communication in both directions, which is ideal for applications like chat apps, live notifications, and online gaming.

    72

    What are Server-Sent Events (SSE)?

    SSE is a technology where a server can push data to a client automatically once an initial client connection has been established. It's a one-way communication channel from server to client, and it's simpler than WebSockets. It's ideal for things like live stock tickers or news feeds.

    73

    What is debouncing?

    Debouncing is a programming practice used to ensure that a function is not called too frequently. It groups a burst of sequential calls into a single one. A debounced function will only run after a certain amount of time has passed without it being called. Use case: a search bar that only fetches results after the user has stopped typing for 300ms.

    74

    What is throttling?

    Throttling is a practice that ensures a function is executed at most once every specified period. A throttled function will run, then wait for the specified interval before it can run again, regardless of how many times it was called during that interval. Use case: ensuring a scroll event handler doesn't fire more than once every 100ms.

    75

    How would you implement a simple `Promise` from scratch?

    This is a complex question testing deep knowledge. A simplified implementation would involve a class with:

    • A state (pending, fulfilled, rejected).
    • A value.
    • Arrays for onFulfilled and onRejected callbacks.
    • A then method that pushes callbacks to the arrays.
    • An executor function that takes resolve and reject functions, which change the state and trigger the stored callbacks.

    76

    What is the DOM?

    The Document Object Model (DOM) is a tree-like representation of an HTML document. It's an API that allows programs to read and manipulate the content, structure, and style of a web page.

    77

    What is the difference between `window` and `document`?

    • window: The global object in the browser. It represents the browser window or tab. All global variables and functions are properties of window.
    • document: A property of the window object. It represents the HTML document loaded in that window.
    78

    What is event delegation?

    Event delegation is a technique where you add a single event listener to a parent element to handle events for all of its children. When a child element is clicked, the event "bubbles" up to the parent. The parent can then check the event.target property to determine which child was actually clicked. This is more efficient than adding an event listener to every child element, especially for dynamic lists.

    79

    Explain event bubbling and capturing.

    These are the two phases of DOM event propagation.

    1. Capturing Phase: The event travels from the window object down through the DOM tree to the target element.
    2. Bubbling Phase: The event travels back up from the target element through the DOM tree to the window object. By default, event listeners are handled in the bubbling phase. You can listen in the capturing phase by setting the third argument of addEventListener to true.
    80

    `innerHTML` vs. `innerText` vs. `textContent`.

    • innerHTML: Gets or sets the HTML content inside an element. It can be a security risk (XSS) if you set it with untrusted content.
    • innerText: Gets or sets the "rendered" text content. It is style-aware and will not show text from hidden elements.
    • textContent: Gets or sets the raw text content of a node and its descendants, including text from hidden elements and <script> tags. It has better performance than innerText.
    81

    What is the difference between `localStorage` and `sessionStorage`?

    Both are part of the Web Storage API for storing key-value pairs.

    • localStorage: Persists data even after the browser is closed and reopened. The data has no expiration time.
    • sessionStorage: Stores data only for a single session. The data is cleared when the tab or window is closed.
    82

    What are cookies?

    Cookies are small pieces of data stored on the client's computer by the web browser. They are sent back to the server with every subsequent request. They are used for session management, personalization, and tracking. They have size limits and are sent with every HTTP request, which can impact performance.

    83

    `localStorage` vs. Cookies.

    FeaturelocalStorageCookies
    Capacity5-10 MB~4 KB
    AccessibilityClient-side onlyClient and Server
    ExpirationNever expiresManually set
    HTTP RequestsNot sent with requestsSent with every request
    84

    What is the Shadow DOM?

    The Shadow DOM is a web standard that allows for encapsulated DOM and CSS in a web component. It creates a hidden, separate DOM tree attached to an element. This is crucial for creating reusable components (like a <video> tag) without worrying about styles or scripts leaking in or out.

    85

    What are data attributes?

    Data attributes (data-*) are a way to store custom data private to the page or application on standard HTML elements. You can access them in JavaScript using the dataset property.

    86

    What is the difference between `load` and `DOMContentLoaded` events?

    • DOMContentLoaded: Fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
    • load: Fires when the whole page has loaded, including all dependent resources such as stylesheets and images.
    87

    How can you optimize a website's assets?

    • Minification: Removing all unnecessary characters from source code (like whitespace, comments).
    • Concatenation: Combining multiple files into a single file to reduce HTTP requests.
    • Image Optimization: Compressing images and using modern formats like WebP.
    • Lazy Loading: Defer loading of non-critical resources (like images below the fold) until they are needed.
    • CDN (Content Delivery Network): Serving assets from a network of servers geographically closer to the user.
    88

    What are Service Workers?

    A Service Worker is a script that your browser runs in the background, separate from a web page. They enable features like offline capabilities, background sync, and push notifications. They act as a proxy server, intercepting network requests and handling them as you see fit.

    89

    What is the `Intersection Observer` API?

    This API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport. It's a highly efficient way to implement features like lazy-loading images or infinite scrolling.

    90

    What is the `Resize Observer` API?

    This API provides a performant mechanism by which code can monitor an element for changes to its size, with notifications being delivered to the observer each time the size changes.


    91

    How would you implement a `debounce` function from scratch?

    function debounce(func, delay) { let timeoutId; return function(...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => { func.apply(this, args); }, delay); }; }
    92

    How would you implement a `throttle` function from scratch?

    function throttle(func, limit) { let inThrottle; return function(...args) { if (!inThrottle) { func.apply(this, args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } }; }
    93

    How would you find all the permutations of a string?

    This is a classic recursion problem. The base case is a string of length 1. The recursive step involves taking each character, finding all permutations of the remaining characters, and prepending the character to each of those permutations.

    94

    How would you implement a basic caching/memoization function?

    Memoization is an optimization technique used to speed up function calls by caching the results of expensive function calls and returning the cached result when the same inputs occur again.

    function memoize(func) { const cache = {}; return function(...args) { const key = JSON.stringify(args); if (cache[key]) { return cache[key]; } const result = func(...args); cache[key] = result; return result; }; }
    95

    How would you flatten a deeply nested array?

    // Using ES2019's flat() method const nested = [1, [2, [3, [4]]]]; console.log(nested.flat(Infinity)); // [1, 2, 3, 4] // Recursive approach function flatten(arr) { let flatArr = []; arr.forEach(item => { if (Array.isArray(item)) { flatArr = flatArr.concat(flatten(item)); } else { flatArr.push(item); } }); return flatArr; }
    96

    What is the difference between imperative and declarative programming?

    • Imperative: Focuses on how to achieve a result. You write explicit steps and control the flow of the program (e.g., using for loops, if statements).
    • Declarative: Focuses on what the result should be. You describe the desired outcome, and the language/engine figures out how to get there (e.g., SQL queries, array methods like map and filter, HTML).
    97

    How would you design a client-side routing system for a Single Page Application (SPA)?

    1. History API: Use the history.pushState() method to change the URL in the browser without causing a page refresh.
    2. Event Listener: Listen for the popstate event, which fires when the user navigates using the browser's back/forward buttons.
    3. Route Matching: Create a system to map URL paths to specific components or views. When the URL changes, match the path to a route and render the corresponding view into the DOM.
    98

    How would you approach designing a scalable front-end architecture?

    • Component-Based Architecture: Break the UI into small, reusable, and independent components (e.g., using React, Vue, or Angular).
    • State Management: Use a centralized state management solution (like Redux, Vuex, or Zustand) to handle application state predictably.
    • Code Splitting: Use a bundler like Webpack or Vite to split the code into smaller chunks that can be loaded on demand.
    • Design System: Create a consistent design system with reusable UI components and styles.
    • Testing: Implement a robust testing strategy with unit, integration, and end-to-end tests.
    99

    Design a simple auto-complete/type-ahead component.

    1. Input Element: An <input> field for the user to type in.
    2. Event Listener: Attach an input event listener to the input field.
    3. Debouncing: Wrap the event handler in a debounce function to avoid making excessive API calls.
    4. API Call: Inside the debounced handler, fetch data from an API based on the input's value.
    5. State Management: Store the fetched suggestions in the component's state.
    6. Rendering: Render the list of suggestions below the input field.
    7. Accessibility: Ensure it's accessible using ARIA attributes.
    100

    How would you ensure the security of a web application?

    • Prevent XSS (Cross-Site Scripting): Sanitize user input and avoid using innerHTML with untrusted data. Use Content Security Policy (CSP) headers.
    • Prevent CSRF (Cross-Site Request Forgery): Use anti-CSRF tokens.
    • Use HTTPS: Encrypt all communication between the client and server.
    • Secure Authentication: Store passwords securely (hashed and salted on the server), use JWTs or sessions correctly, and implement secure password reset flows.
    • Dependency Management: Regularly scan dependencies for known vulnerabilities.

    For more in-depth tutorials and resources, check out my blog and social media:

    🔗 Blog: https://codewiz.info

    🔗 LinkedIn: https://www.linkedin.com/in/code-wiz-740370302/

    🔗 Medium: https://medium.com/@code.wizzard01

    🔗 Github: https://github.com/CodeWizzard01

    Summarise

    Transform Your Learning

    Get instant AI-powered summaries of YouTube videos and websites. Save time while enhancing your learning experience.

    Instant video summaries
    Smart insights extraction
    Channel tracking