CandidateToHR

Top JavaScript Interview Questions Interview Questions | CandidateToHR

Crack your frontend JavaScript interview. Covers closures, event loop, promises, ES6+, and tricky core JS concepts.


CandidateToHR provides highly optimized, professional tech career resources. Build, customize, and analyze your tech career credentials completely free.

Master core JavaScript. 50 real-world questions covering the Event Loop, Closures, and Async programming.

Top Interview Questions & Answers

Beginner Interview Questions

Q: What are the different data types in JavaScript?
A: JavaScript has primitive and non-primitive data types. Primitives include String, Number, Boolean, Undefined, Null, Symbol, and BigInt. Non-primitives are Objects (which include Arrays and Functions). Primitives are immutable and passed by value, while Objects are mutable and passed by reference.
Q: Explain the difference between `var`, `let`, and `const`.
A: `var` is function-scoped and hoisted with an initial value of undefined. `let` and `const` are block-scoped and hoisted but reside in a 'Temporal Dead Zone' until initialized. `let` allows reassignment, whereas `const` requires an initial value and cannot be reassigned (though objects/arrays declared with const can still be mutated).
Q: What is hoisting in JavaScript?
A: Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope before code execution. Only declarations are hoisted, not initializations. This allows functions to be called before they are declared. `let` and `const` are hoisted but remain uninitialized, resulting in a ReferenceError if accessed early.
Q: What is the difference between `==` and `===`?
A: `==` is the abstract equality operator; it performs type coercion before comparison (e.g., `'5' == 5` is true). `===` is the strict equality operator; it checks both value and type without coercion (e.g., `'5' === 5` is false). Best practice is to always use `===` to prevent unexpected bugs.
Q: Explain `null` vs `undefined`.
A: `undefined` means a variable has been declared but has not yet been assigned a value. It is the default value for uninitialized variables. `null` is an assignment value representing the intentional absence of any object value. Interestingly, `typeof undefined` is 'undefined', but `typeof null` is 'object' (a known JavaScript bug).
Q: What is a closure?
A: A closure is a function bundled together with references to its surrounding state (the lexical environment). In JavaScript, closures are created every time a function is created. It gives a function access to its outer scope, even after the outer function has returned. Closures are heavily used for data privacy and function currying.
Q: What are template literals?
A: Introduced in ES6, template literals are string literals allowing embedded expressions. They use backticks (``) instead of quotes. They enable multi-line strings and string interpolation using the `${expression}` syntax, replacing cumbersome string concatenation.
Q: How do arrow functions differ from regular functions?
A: Arrow functions (`() => {}`) provide a shorter syntax and, crucially, do not have their own `this`, `arguments`, `super`, or `new.target`. They inherit `this` from the parent scope (lexical scoping). Therefore, they cannot be used as constructors and are poorly suited as object methods.
Q: What is destructuring assignment?
A: Destructuring is an ES6 feature that allows you to unpack values from arrays, or properties from objects, into distinct variables. For example, `const { name, age } = user;` extracts properties from the `user` object. It makes the code cleaner and more readable.
Q: What is the Spread operator?
A: The spread operator (`...`) allows an iterable (like an array or string) or an object to be expanded in places where zero or more arguments or elements are expected. It is commonly used to copy arrays (`[...arr]`), merge objects (`{...obj1, ...obj2}`), and pass array elements as arguments to a function.
Q: What are Default Parameters?
A: Default function parameters allow named parameters to be initialized with default values if no value or `undefined` is passed to the function. Example: `function multiply(a, b = 1) { return a * b; }`.
Q: What is `typeof` operator used for?
A: The `typeof` operator returns a string indicating the type of the unevaluated operand. Common returns include 'string', 'number', 'boolean', 'undefined', 'object', and 'function'. Note that `typeof []` and `typeof null` both return 'object'.
Q: Explain `map()`, `filter()`, and `reduce()`.
A: These are array methods. `map()` creates a new array by applying a function to every element. `filter()` creates a new array with all elements that pass a test implemented by the provided function. `reduce()` executes a reducer function on each element, resulting in a single output value.
Q: What is the DOM?
A: The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects.
Q: What is Event Delegation?
A: Event delegation is a pattern based on Event Bubbling. Instead of attaching event listeners to multiple child elements, you attach a single event listener to a parent element. The parent listens for events bubbling up from its children and uses `event.target` to determine which child triggered it.
Q: What is strict mode (`'use strict'`)?
A: Strict mode is a way to opt in to a restricted variant of JavaScript. It eliminates some JS silent errors by changing them to throw errors, fixes mistakes that make it difficult for JavaScript engines to perform optimizations, and prohibits some syntax likely to be defined in future ECMAScript versions.
Q: What is NaN?
A: NaN stands for 'Not-a-Number'. It is a property of the global object representing a value that is not a legal number. It typically results from invalid math operations (e.g., `0 / 0` or `'string' * 5`). Interestingly, `typeof NaN` returns 'number', and `NaN === NaN` is false.

Intermediate Interview Questions

Q: Explain the JavaScript Event Loop.
A: JavaScript is single-threaded. The Event Loop enables non-blocking asynchronous behavior. It consists of the Call Stack, Web APIs, Macrotask Queue, and Microtask Queue. When an async operation finishes, its callback goes to a queue. The Event Loop continuously checks if the Call Stack is empty. If it is, it pushes tasks from the Microtask queue (like Promises) first, then the Macrotask queue (like setTimeout), ensuring smooth execution.
Q: What is the difference between Macrotasks and Microtasks?
A: Microtasks (Promises, `MutationObserver`, `process.nextTick` in Node) have higher priority than Macrotasks (`setTimeout`, `setInterval`, UI rendering, I/O). After the current call stack clears, the Event Loop empties the entire Microtask queue before processing the next single Macrotask. This means infinite Microtasks can block the rendering pipeline.
Q: What are Promises?
A: A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. It has three states: Pending, Fulfilled, and Rejected. They solve 'callback hell' by allowing chaining via `.then()` and `.catch()`, making asynchronous code much more readable.
Q: Explain `async` and `await`.
A: Introduced in ES8, `async/await` is syntactic sugar over Promises. Marking a function as `async` ensures it returns a Promise. Inside an async function, you can use the `await` keyword to pause execution until a Promise settles. This makes asynchronous code look and behave like synchronous code.
Q: What is `this` in JavaScript?
A: The value of `this` depends on how a function is called, not where it is defined. In a method, `this` refers to the owner object. In a standard function, `this` refers to the global object (or `undefined` in strict mode). Arrow functions don't bind `this`; they inherit it from the lexical scope.
Q: How do `call()`, `apply()`, and `bind()` work?
A: All three explicitly set the `this` context for a function. `call()` invokes the function with a given `this` value and arguments passed individually. `apply()` is identical to `call()`, but arguments are passed as an array. `bind()` does not invoke the function immediately; it returns a new function with a permanently bound `this` value.
Q: What is Prototypal Inheritance?
A: Unlike class-based languages, JavaScript uses prototypes. Every object has an internal link to another object called its prototype. When accessing a property on an object, JS first looks at the object itself, then traverses up the prototype chain until it finds the property or reaches `null`.
Q: What are ES6 Modules?
A: ES6 Modules (`import` and `export`) allow you to split code into separate files. Modules run in strict mode by default, have their own top-level scope (preventing global namespace pollution), and are executed deferentially by the browser.
Q: Explain Debouncing vs. Throttling.
A: Both are techniques to optimize performance by limiting the execution rate of functions (like window resizing or search inputs). Debouncing delays function execution until a certain time has passed since the *last* invocation. Throttling guarantees execution at regular intervals, regardless of how many times the event fires.
Q: What is Currying?
A: Currying is a functional programming technique where a function with multiple arguments is transformed into a sequence of nested functions, each taking a single argument. E.g., `add(a, b)` becomes `add(a)(b)`. It is highly useful for function composition and partial application.
Q: What is a generator function?
A: A generator function (defined using `function*`) can pause its execution and be resumed later. It uses the `yield` keyword to return values one by one. When called, it doesn't execute its body immediately; instead, it returns an iterator object.
Q: How does Garbage Collection work in JS?
A: JavaScript automatically allocates and frees memory. Modern engines use a 'Mark-and-Sweep' algorithm. The garbage collector periodically identifies 'roots' (global variables) and traverses all references. Any object in memory that cannot be reached from the roots is marked for deletion and swept away.
Q: What are Set and Map?
A: Introduced in ES6, `Set` is a collection of unique values of any type. `Map` is a collection of keyed data items, similar to an Object, but Map allows keys of any type (including objects and functions) and maintains insertion order.
Q: Explain Event Bubbling and Capturing.
A: They describe the phases of event propagation in the DOM. In Capturing (trickling), the event travels from the root down to the target element. In Bubbling, the event travels from the target element up back to the root. By default, most event handlers are attached to the bubbling phase.
Q: What is the Temporal Dead Zone (TDZ)?
A: The TDZ is the period of time during which `let` and `const` variables exist but cannot be accessed. It starts at the beginning of the block scope and ends when the variable is declared and initialized. Accessing the variable in the TDZ throws a ReferenceError.
Q: Deep Copy vs Shallow Copy?
A: A shallow copy duplicates the top-level properties of an object, but nested objects remain references to the original. (e.g., using `...spread` or `Object.assign()`). A deep copy duplicates all levels, creating entirely disconnected objects (e.g., using `structuredClone()` or `JSON.parse(JSON.stringify(obj))`).
Q: What is IIFE?
A: IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined: `(function() { /* code */ })();`. It creates a private scope to avoid polluting the global namespace.

Advanced Interview Questions

Q: Explain the V8 Engine architecture and JIT Compilation.
A: V8 is Google's open-source high-performance JS engine. It uses Just-In-Time (JIT) compilation, compiling JS directly to machine code rather than using an interpreter. It employs an interpreter (Ignition) for fast startup and an optimizing compiler (TurboFan) that optimizes hot code paths dynamically based on runtime profiling.
Q: How do WeakMap and WeakSet differ from Map and Set?
A: WeakMaps and WeakSets only accept Objects as keys/values, not primitives. Crucially, they hold 'weak' references to these objects. If there are no other references to the object, the garbage collector will remove it, preventing memory leaks. Because they can be garbage collected at any time, WeakMaps are not iterable.
Q: What is tail call optimization (TCO)?
A: TCO is an engine-level optimization where if the last action of a function is to return the result of calling another function (a tail call), the engine reuses the current stack frame instead of pushing a new one. This prevents Stack Overflow errors in deep recursive functions. Currently, support in V8/Chrome is limited.
Q: Explain the Proxy object.
A: The Proxy object enables you to create a custom wrapper around another object, allowing you to intercept and redefine fundamental operations like property lookup (`get`), assignment (`set`), enumeration, and function invocation. It is heavily used in modern frameworks like Vue 3 for reactivity.
Q: How do you implement a polyfill for `Promise.all`?
A: You return a new Promise that takes an array of promises. You iterate over the array, attaching `.then()` to each. You keep a counter of resolved promises and an array of results. When a promise resolves, place its result in the correct index and increment the counter. If the counter equals the input array length, `resolve()` the main promise. If any `.catch()` fires, `reject()` the main promise.
Q: What are Web Workers?
A: Web Workers allow you to run JavaScript in background threads. They run entirely independent of the main UI thread, meaning heavy CPU calculations won't block the UI. Workers cannot manipulate the DOM directly. Communication between the main thread and workers is handled via the `postMessage` API.
Q: Explain Cross-Origin Resource Sharing (CORS).
A: CORS is an HTTP-header based security mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. Browsers enforce the Same-Origin Policy. To bypass it for API calls, the server must respond with `Access-Control-Allow-Origin` headers. Complex requests require a 'Preflight' `OPTIONS` request.
Q: What is the Reflect API?
A: Reflect is a built-in object that provides methods for interceptable JavaScript operations. The methods are the same as those of proxy handlers. It is designed to work closely with Proxies, providing a cleaner way to forward default operations to the target object inside a Proxy trap.
Q: How does `requestAnimationFrame` work?
A: `requestAnimationFrame` tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. It syncs with the monitor's refresh rate (typically 60 times per second), pausing automatically when the tab is inactive, drastically saving battery and CPU.
Q: Explain Service Workers and their lifecycle.
A: Service Workers act as network proxies, sitting between the web app, the browser, and the network. They enable Offline experiences, Background Sync, and Push Notifications. The lifecycle consists of Registration, Installation (caching static assets), Activation (cleaning up old caches), and finally, intercepting `fetch` events.
Q: What is memoization and how would you write a memoize function?
A: Memoization is an optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur. To implement: create a closure holding a `cache` object. Return a function that stringifies its arguments to create a cache key. If the key exists, return the cached value. If not, execute the original function, store the result in the cache, and return it.
Q: What are Symbol properties used for?
A: Symbols are unique, immutable primitive values. They are often used to add unique property keys to objects that won't collide with keys any other code might add, and are hidden from normal mechanisms like `for...in` or `Object.keys()`. They are used heavily in metaprogramming (e.g., `Symbol.iterator`).
Q: Explain `Object.defineProperty` and Accessor Descriptors.
A: `Object.defineProperty` allows precise addition or modification of a property on an object. You can define property descriptors to make properties read-only (`writable: false`), hidden from loops (`enumerable: false`), or un-deletable (`configurable: false`). Accessor descriptors allow you to define custom `get` and `set` functions for a property.
Q: How does `structuredClone()` work?
A: `structuredClone()` is a modern, built-in global function that creates a deep clone of a given value. Unlike `JSON.parse(JSON.stringify())`, it supports circular references, Dates, Sets, Maps, and TypedArrays. It cannot clone functions or DOM nodes.
Q: What is the difference between `Array.prototype.forEach` and a `for...of` loop with async/await?
A: `forEach` expects a synchronous callback. If you pass an `async` function to `forEach`, it fires them off but does NOT `await` them. The loop finishes immediately while the promises are still pending. A `for...of` loop genuinely halts at the `await` keyword, executing asynchronous operations sequentially.
Q: How do memory leaks occur in closures?
A: Closures retain references to their outer scope's variables. If an outer function defines a massive object and an inner function closes over it, that object cannot be garbage collected as long as the inner function is kept alive (e.g., bound to a global event listener). V8 performs 'closure scope optimization' to only retain variables actually accessed, but poor scoping can still cause massive leaks.

Frequently Asked Questions

How many questions are covered in this guide?

This guide covers 50+ of the most frequently asked questions.

Are these questions suitable for beginners?

Yes, the guide is divided into beginner, intermediate, and advanced sections.

How often is this guide updated?

We update our interview questions quarterly to ensure they reflect current industry standards.

Should I memorize the answers?

No, it is better to understand the underlying concepts rather than memorizing answers word-for-word.

Are these questions asked at FAANG companies?

Yes, many of these questions are standard in interviews at top tech companies like Google, Amazon, and Meta.


Related Resources & Next Steps