Here are 100 JavaScript interview questions and answers, covering fundamentals, ES6, DOM manipulation, asynchronous programming, objects, arrays, functions, scope, closures, promises, and more. Each question is in bold, followed by a detailed answer. No dividing lines.
What is JavaScript and what are its key features?
Answer: JavaScript is a high-level, interpreted programming language originally designed for web browsers. Key features: event-driven, functional and object-oriented paradigms, dynamic typing, first-class functions, prototype-based inheritance, asynchronous capabilities (event loop), and automatic garbage collection.
What are the different data types in JavaScript?
Answer: Primitive types: string, number, boolean, null, undefined, symbol (ES6), bigint (ES2020). Reference type: object (including arrays, functions, dates, regular expressions, maps, sets). Primitives are immutable and stored by value; objects stored by reference.
What is the difference between undefined and null?
Answer: undefined means a variable has been declared but not assigned a value. null is an intentional assignment representing “no value” or “empty object”. typeof undefined returns “undefined”; typeof null returns “object” (historical bug). They are loosely equal (null == undefined true) but not strictly equal (=== false).
What is the difference between == and ===?
Answer: == (abstract equality) compares values after type coercion (e.g., 0 == false is true). === (strict equality) compares both value and type without coercion. Always use === to avoid unexpected bugs.
What is hoisting in JavaScript?
Answer: Hoisting moves declarations to the top of their containing scope during compilation. var variables are hoisted with undefined; function declarations are hoisted fully (can be called before definition). let and const are hoisted but not initialized (temporal dead zone), causing ReferenceError if accessed before declaration.
What is the difference between var, let, and const?
Answer: var is function-scoped, can be redeclared, hoisted with undefined. let is block-scoped, cannot be redeclared in same scope, hoisted but not initialized (TDZ). const is block-scoped, cannot be reassigned (though object properties can be mutated), must be initialized at declaration. Use let and const over var.
What is the temporal dead zone (TDZ)?
Answer: The TDZ is the period between entering a scope and the point where a let or const variable is initialized. Accessing the variable during TDZ throws a ReferenceError. It prevents accidental usage before declaration.
What are closures in JavaScript?
Answer: A closure is a function that remembers and accesses its lexical scope even after the outer function has returned. Example: function outer() { let x = 10; return function inner() { console.log(x); }; }. Closures enable data privacy, currying, and module patterns.
Explain the this keyword in JavaScript. How is its value determined?
Answer: this refers to the execution context. Value depends on call site:
– In a method: the object.
– Alone (non-strict): global object (window).
– In strict mode: undefined.
– Event listener: the element.
– Arrow function: lexically inherited from outer scope.
– With call, apply, bind: explicitly set.
– Constructor (new): the new instance.
What is the difference between call, apply, and bind?
Answer: call invokes a function with a given this and arguments individually. apply does the same but takes arguments as an array. bind returns a new function with permanently bound this and optional preset arguments, without immediate invocation.
What are arrow functions and how are they different from regular functions?
Answer: Arrow functions (() => {}) are shorter and do not have their own this, arguments, super, or new.target. They cannot be used as constructors (no new). Their this is lexically bound to the surrounding scope, making them ideal for callbacks.
What is a promise in JavaScript?
Answer: A Promise represents the eventual completion (or failure) of an asynchronous operation. States: pending, fulfilled (resolved), rejected. Methods: .then() (success), .catch() (error), .finally() (cleanup). Promises enable chaining and avoid callback hell.
What is async/await and how does it work?
Answer: async functions return a promise. await pauses the execution of the async function until the awaited promise settles, then resumes with the resolved value. Error handling uses try/catch. async/await is syntactic sugar over promises, making asynchronous code look synchronous.
What is the event loop in JavaScript?
Answer: The event loop allows JavaScript (single‑threaded) to handle asynchronous operations. It continuously checks the call stack and the callback queue. When the stack is empty, it pushes callbacks from the queue onto the stack. It also handles microtasks (promises) before macrotasks (setTimeout, I/O).
What is the difference between setTimeout and setInterval?
Answer: setTimeout executes a callback once after a delay (in milliseconds). setInterval repeatedly executes a callback every interval. Use clearTimeout and clearInterval to cancel. Neither guarantees exact timing; they queue tasks.
What are the differences between null and undefined?
Answer: (Covered earlier) Briefly: undefined is default unassigned; null is intentional empty value.
What are the different ways to create an object in JavaScript?
Answer: Object literal: { key: 'value' }. Constructor: new Object(). Object.create(): Object.create(proto). Class (ES6): class MyClass { constructor() {} }. Function constructor: function Person(name) { this.name = name; }.
What is prototype inheritance in JavaScript?
Answer: Every JavaScript object has an internal [[Prototype]] (accessed via __proto__ or Object.getPrototypeOf()). Properties looked up along the prototype chain. Functions have a prototype property used when called with new. Inheritance is achieved by setting an object’s prototype to another object.
What is the new keyword doing?
Answer: new creates a new object, sets its prototype to the constructor’s prototype property, executes the constructor with this bound to the new object, and returns the object (unless constructor returns an object).
What is the difference between a shallow copy and a deep copy?
Answer: Shallow copy copies only top-level properties; nested objects are still referenced. Methods: spread {...obj}, Object.assign(). Deep copy creates independent copy of all levels. Methods: JSON.parse(JSON.stringify(obj)) (limited, fails with functions and circular references), structuredClone(), or libraries like Lodash’s .cloneDeep().
What is the spread operator (...)?
Answer: The spread operator expands iterables (arrays, strings, objects) into individual elements. Examples: [...arr], {...obj}, Math.max(...arr). Used for copying, merging, and function arguments.
What are template literals?
Answer: Template literals use backticks (`) and allow embedded expressions with ${expression}. They support multi-line strings without escaping and string interpolation.
What are destructuring assignments?
Answer: Destructuring extracts values from arrays or properties from objects into distinct variables. Array: const [a, b] = [1, 2];. Object: const { name, age } = person;. Default values and renaming possible.
What are default parameters in functions?
Answer: Default parameters allow setting default values for function parameters if undefined is passed. Example: function greet(name = 'Guest') { console.log(Hello ${name}); }. Avoids checking undefined manually.
What are rest parameters (...)?
Answer: Rest parameters collect remaining arguments into an array. Appears at the last parameter. Example: function sum(...numbers) { return numbers.reduce((a,b)=>a+b,0); }.
What is the difference between a for...in and for...of loop?
Answer: for...in iterates over enumerable property keys (including inherited) of an object. Should not be used for arrays (iterates indices as strings). for...of iterates over iterable values (arrays, strings, maps, sets). Use for...of for arrays.
What is the map() method for arrays?
Answer: map() creates a new array by applying a callback function to each element of the original array. It does not mutate the original array. Example: [1,2,3].map(x => x * 2) // [2,4,6].
What is the filter() method?
Answer: filter() creates a new array with all elements that pass the test implemented by the callback. Example: [1,2,3,4].filter(x => x > 2) // [3,4].
What is the reduce() method?
Answer: reduce() executes a reducer function on each element, resulting in a single output value. Syntax: array.reduce((accumulator, currentValue) => accumulator + currentValue, initialValue). Used for summing, grouping, flattening.
What is the difference between forEach and map?
Answer: forEach iterates over array elements, returns undefined, and is used for side effects (e.g., logging, modifying external variables). map returns a new array of the same length for transformation. forEach cannot be chained; map can.
What are higher-order functions?
Answer: Higher-order functions are functions that take other functions as arguments or return a function. Examples: map, filter, reduce, setTimeout, addEventListener. They enable functional programming.
What is a callback function?
Answer: A callback is a function passed as an argument to another function, executed later (after an asynchronous operation or event). Used with setTimeout, event listeners, AJAX, and array methods.
What is callback hell and how to avoid it?
Answer: Callback hell is deeply nested callbacks leading to unreadable code. Avoid by using promises, async/await, or modularization. Example of hell: getData(function(a){ getMore(a, function(b){ ... }); });.
What is a promise chain?
Answer: Chaining promises with .then() allows sequential asynchronous operations. Each .then() returns a new promise, enabling the next step. Error handling with a single .catch() at the end.
What is the difference between Promise.all, Promise.race, and Promise.allSettled?
Answer: Promise.all rejects if any promise rejects; resolves when all resolve (array of results). Promise.race settles as soon as any promise settles (first result or error). Promise.allSettled waits for all to settle, never rejects; returns array of objects with status and value/reason.
What is the difference between Promise.any and Promise.race?
Answer: Promise.any resolves with the first fulfilled promise; ignores rejections. If all reject, it rejects with an AggregateError. Promise.race settles on the first promise to settle (either fulfilled or rejected).
What is a generator function?
Answer: Generator functions (function*) can be paused and resumed, yielding multiple values using yield. They return an iterator object with next(). Useful for lazy evaluation and custom iteration.
What are Map and WeakMap?
Answer: Map stores key-value pairs where keys can be any type (not just strings). Iterable, has size property. WeakMap holds “weak” references to keys (objects only), does not prevent garbage collection, and is not iterable. Use for private data.
What are Set and WeakSet?
Answer: Set stores unique values of any type, iterable. WeakSet stores unique objects with weak references, not iterable, does not prevent garbage collection.
What is the difference between slice and splice?
Answer: slice(start, end) returns a shallow copy of a portion of an array without modifying the original. splice(start, deleteCount, items) changes the original array by removing/replacing elements; returns the removed items.
How do you check if a variable is an array?
Answer: Array.isArray(variable) – preferred because typeof returns “object” for arrays. Also variable instanceof Array (works across frames? less reliable).
What is the difference between Object.freeze() and Object.seal()?
Answer: Object.freeze() prevents adding, deleting, or modifying existing properties (deep freeze not automatic). Object.seal() prevents adding/deleting but allows modifying existing properties. Both make object non-extensible.
What is event delegation?
Answer: Event delegation attaches a single event listener to a parent element instead of multiple listeners on children. The listener uses event targeting (event.target) to handle events for current and future children. Improves performance and handles dynamic content.
What is event bubbling and capturing?
Answer: Event propagation has three phases: capturing (window to target), target, bubbling (target to window). Default event listeners use bubbling. Capturing can be enabled by passing true as third argument to addEventListener.
How do you stop event propagation?
Answer: event.stopPropagation() stops further propagation (bubbling or capturing). event.stopImmediatePropagation() also prevents other listeners on the same element from firing.
What is the difference between preventDefault() and stopPropagation()?
Answer: preventDefault() stops the browser’s default action for the event (e.g., form submission, link navigation). stopPropagation() stops the event from moving through the DOM tree. They are independent.
What are Web Workers?
Answer: Web Workers run JavaScript in background threads separate from the main thread, allowing heavy computations without blocking the UI. They cannot access DOM directly. Communicate via postMessage and onmessage. Workers have limited API access.
What is the localStorage and sessionStorage?
Answer: Both are web storage APIs. localStorage stores data with no expiration; persists across sessions. sessionStorage data is cleared when tab/window is closed. Both are session-specific to origin, limited to ~5-10MB.
What is a cookie and its limitations?
Answer: Cookies are small pieces of data stored in the browser, sent with every HTTP request. Limitations: 4KB size, limited to 20 per domain (browser-specific), can be accessed by JavaScript unless HttpOnly. Used for authentication, tracking, sessions.
What is JSON?
Answer: JSON (JavaScript Object Notation) is a lightweight data interchange format, derived from object syntax. Keys and strings must be double-quoted. Convert with JSON.stringify() (object to JSON) and JSON.parse() (JSON to object).
What is a polyfill?
Answer: A polyfill is a piece of code that provides modern functionality on older browsers that do not support it natively. Example: Array.prototype.includes polyfill or fetch polyfill.
What are modules in JavaScript (ES6)?
Answer: ES6 modules allow exporting/importing code between files. Use export to expose functions, objects, or primitives. Use import to bring them in. Modules are strict by default, have their own scope, and support dynamic imports (import()).
What is the difference between export default and named exports?
Answer: A module can have one default export, imported without curly braces: import myDefault from './module'. Named exports are imported with curly braces: import { named } from './module'. Both can be used together.
What is the purpose of the use strict directive?
Answer: 'use strict' enforces stricter parsing and error handling: eliminates silent errors, prevents accidental globals, forbids with, changes this behavior to undefined in functions (not global), and throws more exceptions. Improves security and performance.
What is a closure? Provide a practical example.
Answer: (Covered earlier) Practical example: a counter function that maintains private state:function createCounter() { let count = 0; return { increment: () => ++count, value: () => count }; }
What is the difference between function declaration and function expression?
Answer: Function declaration: function foo() {} – hoisted (can be called before declaration). Function expression: const foo = function() {} – not hoisted; variable is hoisted but not the assignment. Arrow functions are expressions.
What is an IIFE (Immediately Invoked Function Expression)?
Answer: An IIFE is a function that runs as soon as it is defined. Syntax: (function() { /* code */ })();. Used to create a private scope, avoiding global namespace pollution. ES6 modules and block scoping have made IIFEs less common.
What is a first-class function?
Answer: Functions are first-class citizens: they can be assigned to variables, passed as arguments, returned from other functions, and have properties. This enables higher-order functions and functional programming.
What is memoization?
Answer: Memoization is an optimization technique that caches results of expensive function calls based on inputs. The same input returns cached output. Implement using closures or libraries. Commonly used in recursive functions (fibonacci) and React useMemo.
What is recursion?
Answer: Recursion is when a function calls itself until a base condition is met. Example: factorial function fact(n) { return n <= 1 ? 1 : n * fact(n-1); }. Risk of stack overflow without base case.
What is the difference between arguments object and rest parameters?
Answer: arguments is an array-like object (not a real array) available inside non-arrow functions, containing all passed arguments. Rest parameters (...args) give a true array and only include extra arguments not captured by named parameters. Use rest parameters in modern code.
What are symbols in JavaScript?
Answer: Symbol is a primitive type introduced in ES6, used to create unique identifiers. Every symbol is guaranteed to be unique. Used as object property keys to avoid name collisions, especially for built-in properties (e.g., Symbol.iterator).
What are iterators and iterables?
Answer: An iterable is an object that implements the @@iterator method (e.g., arrays, strings, maps, sets). An iterator is an object with a next() method returning { value, done }. Use for...of to iterate.
What is the spread operator vs rest parameter?
Answer: Spread expands an iterable in places like function calls or array literals: const arr2 = [...arr1]. Rest collects arguments into an array in function definitions: function(...args){}. Both use ... syntax but context differs.
What are the falsy values in JavaScript?
Answer: Falsy values: false, 0, -0, 0n (bigint), "" (empty string), null, undefined, NaN. Everything else is truthy.
What is the difference between Object.keys(), Object.values(), and Object.entries()?
Answer: Object.keys(obj) returns array of enumerable property names. Object.values(obj) returns array of property values. Object.entries(obj) returns array of [key, value] pairs. All ignore symbol-keyed properties.
What is the typeof operator?
Answer: typeof returns a string indicating the type of the operand. Examples: typeof 42 → “number”, typeof "hello" → “string”, typeof true → “boolean”, typeof undefined → “undefined”, typeof null → “object”, typeof {} → “object”, typeof [] → “object”, typeof function(){} → “function”.
What is the instanceof operator?
Answer: instanceof checks if an object is an instance of a specified constructor (or its prototype chain). Example: myArray instanceof Array returns true. Not reliable across iframes or for primitive wrappers.
What is the difference between == and Object.is()?
Answer: Object.is() is similar to === but with differences: Object.is(NaN, NaN) is true; === gives false. Object.is(+0, -0) is false; === gives true. Use Object.is() for more precise equality.
What is a trampoline function?
Answer: A trampoline is a technique to optimize recursion and prevent stack overflow. It repeatedly calls functions that return other functions (or final result), flattening recursion into a loop. Used in functional programming.
What is a debounce function and how would you implement it?
Answer: Debounce limits the rate at which a function executes, delaying it until a pause occurs. Useful for search inputs. Implementation:
javascript
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
What is a throttle function and how would you implement it?
Answer: Throttle ensures a function executes at most once per specified interval. Useful for scroll events. Implementation:
javascript
function throttle(fn, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = setTimeout(() => inThrottle = false, limit);
}
};
}
How do you deep copy an object with circular references?
Answer: Use structuredClone() (modern browsers) or libraries like Lodash’s _.cloneDeep(). Custom implementation requires handling cycles using a WeakMap to track copied references. JSON.parse(JSON.stringify()) fails with circular references.
What is the difference between Object.create() and the new operator?
Answer: Object.create(proto) creates a new object with the specified prototype. new Constructor() creates an object, sets its prototype to Constructor.prototype, and executes the constructor. Object.create allows more flexible prototype chaining without a constructor.
What is the Proxy object?
Answer: Proxy allows intercepting and customizing operations on an object (get, set, deleteProperty, etc.). Used for validation, logging, reactive programming. Example: new Proxy(target, handler).
What is a Reflect object?
Answer: Reflect provides methods for interceptable JavaScript operations (same as proxy handlers). It is a built-in object with static methods like Reflect.get(), Reflect.set(). Makes proxy implementation cleaner.
What are getters and setters?
Answer: Getters (get) and setters (set) are special methods that define how a property is accessed and assigned. They allow computed properties, validation, and side effects. Defined in object literals or classes.
What is the this value inside an arrow function?
Answer: Arrow functions do not have their own this; it is lexically inherited from the enclosing (parent) scope. This makes them ideal for callbacks where you want to preserve the surrounding context.
What is the difference between a setTimeout with delay 0 and process.nextTick (Node.js)?
Answer: setTimeout(fn, 0) queues a macrotask; it runs after the current event loop iteration and after any pending microtasks. process.nextTick(fn) queues a microtask (higher priority) and runs immediately after the current operation, before any I/O or timers.
What is the difference between Promise.then() and Promise.catch()?
Answer: .then(onFulfilled, onRejected) handles both fulfillment and rejection (optional second argument). .catch(onRejected) is syntactic sugar for .then(undefined, onRejected) and only handles rejections. Chaining .catch after .then is common.
What is the finally method in promises?
Answer: .finally(callback) schedules a callback to be executed after the promise settles (either fulfilled or rejected). It is useful for cleanup (e.g., hiding loaders) and does not modify the promise’s resolved value or rejection reason.
What is the difference between Promise.resolve() and new Promise(resolve => resolve())?
Answer: Promise.resolve(value) creates a resolved promise with the given value. new Promise(resolve => resolve(value)) does the same but requires writing the executor function. Promise.resolve is shorthand and also flattens thenable objects.
What are async iterators and how to use them?
Answer: Async iterators allow iterating over data that arrives asynchronously (e.g., streaming). Use for await...of loop. An async iterable has a Symbol.asyncIterator method returning an object with next() returning a promise.
What is a decorator in JavaScript (stage 3 proposal)?
Answer: Decorators are functions that modify classes or class members (methods, fields) at design time. Syntax @decorator. Used for adding metadata, logging, dependency injection. Babel or TypeScript can transpile them.
What is the difference between throw and return in a promise executor?
Answer: In a new Promise executor, throw error is equivalent to calling reject(error). return value resolves the promise with that value. Outside an executor, throw will crash unless caught.
What is the error-first callback pattern (Node.js)?
Answer: A convention where callbacks receive an error object as the first argument, followed by result data. Example: fs.readFile(file, (err, data) => { if (err) handle(err); else process(data); });
What is a TypedArray?
Answer: TypedArrays (e.g., Uint8Array, Float64Array) provide array-like views of binary data buffers (ArrayBuffer). They allow efficient manipulation of raw binary data for WebGL, WebAudio, and file processing.
What is a WeakRef and FinalizationRegistry?
Answer: WeakRef holds a weak reference to an object, allowing garbage collection. FinalizationRegistry registers callbacks to run when objects are garbage collected. Use sparingly, mainly for caching or cleanup.
What is the Intl object?
Answer: Intl provides language-sensitive string comparison, number formatting, date/time formatting, and relative time formatting. Example: new Intl.DateTimeFormat('en-US').format(date).
What is a Set intersection, union, and difference?
Answer: Set methods (proposal, widely supported): set1.intersection(set2), set1.union(set2), set1.difference(set2). Without native methods, implement using loops or spreading to arrays.
What is a Map vs Object – performance and use cases?
Answer: Map: keys can be any type (objects), preserves insertion order, size property, iterable. Better for frequent additions/removals. Object: keys are strings/symbols, not iterable by default, has prototype chain. Use Object for simple records (known string keys), Map for dynamic keys or key-value stores.
What is the performance.now() method?
Answer: performance.now() returns a high-resolution timestamp in milliseconds (with fractional microseconds) relative to page load start. Used for precise timing measurements in logs and benchmarking.
What is the requestAnimationFrame function?
Answer: requestAnimationFrame schedules a function to run before the next repaint, ideal for smooth animations. It pauses when the tab is inactive, saving CPU. Returns an ID for cancellation (cancelAnimationFrame).
What is the difference between innerHTML and textContent?
Answer: innerHTML parses HTML tags and inserts them; can cause XSS if used with unsanitized user input. textContent inserts plain text, escaping HTML entities. Use textContent for text, innerHTML only when you need to insert actual HTML.
What is the difference between insertAdjacentHTML and innerHTML?
Answer: insertAdjacentHTML inserts HTML string at a specific position relative to the element (beforebegin, afterbegin, beforeend, afterend) without invalidating existing references. innerHTML replaces full content, which can break event listeners and DOM references.
What is a service worker?
Answer: A service worker is a script that runs in the browser background, independent of the web page. It enables offline support (caching), push notifications, background sync, and interception of network requests. It is a key part of progressive web apps (PWAs).
What is CORS and how does it affect JavaScript?
Answer: Cross-Origin Resource Sharing (CORS) restricts web pages from making requests to a different domain than the one that served the page (same-origin policy). The server must include appropriate Access-Control-Allow-Origin headers; otherwise, the browser blocks the request and throws an error in JavaScript.
What is eval() and why is it dangerous?
Answer: eval() executes a string as JavaScript code. It is dangerous because it can run arbitrary code, opening XSS vulnerabilities, and slows performance (disables optimizations). Avoid eval; use Function constructor or other safer alternatives.
What is the difference between window.onload and DOMContentLoaded?
Answer: DOMContentLoaded fires when the DOM is fully loaded and parsed, without waiting for stylesheets, images, or subframes. window.load (or window.onload) fires after all resources (images, styles, etc.) are fully loaded. Use DOMContentLoaded to interact with DOM faster.
What are the different console methods?
Answer: console.log(), console.error(), console.warn(), console.table() (displays array/object as table), console.time() / console.timeEnd() (timing), console.group() / console.groupEnd(), console.assert(), console.trace() (stack trace).
What is the debugger keyword?
Answer: debugger; stops JavaScript execution and invokes the debugging interface (if open), allowing inspection of variables and stepping through code. It is a powerful debugging aid.
What are the steps to handle uncaught promise rejections?
Answer: In browsers, listen to unhandledrejection event on window. In Node.js, handle unhandledRejection event on process. Always catch promise rejections with .catch() or try/catch in async functions.
What is the difference between for await...of and regular for...of?
Answer: for...of loops over synchronous iterables. for await...of loops over asynchronous iterables (e.g., streaming data, async generators). Each iteration awaits the promise returned by the next() method.
What is a BigInt and how is it used?
Answer: BigInt is a primitive type for arbitrary precision integers, beyond the Number.MAX_SAFE_INTEGER limit (2⁵³ – 1). Created by appending n to an integer: 123n or using BigInt(123). Cannot mix with Number in arithmetic without explicit conversion.
What is the Number.isNaN() vs isNaN()?
Answer: isNaN() coerces its argument to a number first, so isNaN("hello") returns true (coerces to NaN). Number.isNaN() does not coerce; returns true only if the value is exactly NaN. Use Number.isNaN() for reliable NaN checking.
What is Object.freeze() and why would you use it?
Answer: Object.freeze(obj) prevents adding, deleting, or modifying properties of an object. Useful for creating immutable constants, preventing accidental mutations, and improving predictability. Shallow only (nested objects not frozen).
What is a polyfill for Array.prototype.includes?
Answer:
javascript
if (!Array.prototype.includes) {
Array.prototype.includes = function(searchElement, fromIndex) {
return this.indexOf(searchElement, fromIndex) !== -1;
};
}
What is the difference between String.prototype.slice and String.prototype.substring?
Answer: Both extract parts of a string. slice accepts negative indices (counts from end). substring treats negative indices as 0. slice is more consistent with array slice. Use slice.
What is a custom element in Web Components?
Answer: Custom elements allow developers to define new HTML tags with custom behavior using JavaScript. Define class MyElement extends HTMLElement, then customElements.define('my-element', MyElement). Used with Shadow DOM and templates.
What is Shadow DOM?
Answer: Shadow DOM encapsulates DOM and styling for a component, isolating it from the main document. Creates a separate tree attached to an element. Styles defined inside shadow DOM do not leak out, and external styles do not affect inside (unless specific CSS properties).
What is the Element.closest() method?
Answer: element.closest(selector) traverses the element and its ancestors up the DOM tree until it finds a node that matches the selector. Returns the matching node or null. Useful for event delegation to find specific parent.
What is MutationObserver?
Answer: MutationObserver monitors changes to the DOM (attributes, child list, subtree). It provides a way to react to DOM mutations without polling. Examples: detecting addition of elements, attribute changes. Callback receives list of mutation records.
What is IntersectionObserver?
Answer: IntersectionObserver asynchronously watches for when an element enters or exits the viewport (or a parent element). Used for lazy loading images, infinite scroll, and scroll-triggered animations. It is more performant than scroll event handlers.
What is ResizeObserver?
Answer: ResizeObserver reports changes to an element’s size. Useful for responsive layouts, canvas resizing, and implementing container queries. Unlike window resize event, it observes individual elements.
What is URLSearchParams?
Answer: URLSearchParams provides methods to manipulate query strings. Example: new URLSearchParams(window.location.search).get('param'). Also used for constructing fetch POST bodies.
What is the AbortController and how is it used with fetch?
Answer: AbortController allows aborting one or more fetch requests. Create const controller = new AbortController();, pass signal: controller.signal in fetch options. Call controller.abort() to cancel the request. Also aborts event listeners and streams.
What is the fetch API and how does it handle errors?
Answer: fetch returns a promise that resolves to a Response object. It only rejects on network failures, not on HTTP error status (404, 500). To handle HTTP errors, check !response.ok. Example:
javascript
fetch(url)
.then(res => { if (!res.ok) throw new Error(res.status); return res.json(); })
.catch(err => console.error(err));
What is the difference between localStorage.setItem and sessionStorage.setItem?
Answer: (Covered earlier) localStorage persists across browser sessions; sessionStorage clears when tab closes. Both store strings only; use JSON.stringify/parse for objects.
What is import.meta?
Answer: import.meta is an object providing metadata about the current module. import.meta.url gives the URL of the module file. Useful for constructing relative paths in ES modules.
What is globalThis?
Answer: globalThis provides a standard way to access the global object across environments (window in browsers, global in Node.js, self in workers). Use instead of window or global for cross-platform code.
Why should we hire you as a JavaScript developer?
Answer: I have strong command over core concepts (closures, scope, promises, async patterns), write clean maintainable code, and stay updated with ECMAScript standards. I build efficient, cross-browser solutions and enjoy solving complex problems. I’m eager to contribute to your team with my skills and continuous learning mindset.