Lead Frontend
​
​
Log inSign up
React interview questionsJavaScript interview questionsTypeScript interview questionsCSS interview questionsHTML interview questionsSenior frontend interview questionsLead frontend engineer interview questionsQuestions by topicCompany guides
© 2026 Lead Frontend. Free educational content, provided as is; it may contain errors. Not affiliated with any company or product named on this site.
TermsPrivacyDisclaimerCopyrightLicenses & credits

JavaScript Interview Questions

259 questions with answers

JavaScript rounds are where most frontend interviews start. Expect concept questions (closures, scope, this, prototypes, the event loop, promises) and coding questions where you implement a utility or polyfill such as debounce, Promise.all or deep clone. Every coding question here comes with tests you can run in the browser.

How to prepare

  • Be able to explain closures, scope, hoisting and this with a short code example.
  • Trace the event loop: microtasks vs macrotasks, promises, async/await and timers.
  • Implement the classics from memory: debounce, throttle, Promise.all, deep clone, curry, memoize.
  • Talk through edge cases and complexity before you start coding.

JavaScript Interview Questions

1.Array.prototype.filter

Implement Array.prototype.filter with thisArg support and correct handling of sparse arrays.

JS Functions
Easy
10 min

2.Array.prototype.flat

Implement Array.prototype.flat with a depth argument, hole removal and an iterative variant.

JS Functions
Medium
15 min

3.Array.prototype.map

Implement Array.prototype.map, keeping holes in sparse arrays and supporting thisArg.

JS Functions
Easy
10 min

4.Array.prototype.reduce

Implement Array.prototype.reduce, including the no-initial-value rules and sparse arrays.

JS Functions
Easy
15 min

5.Backbone Model

Build an observable Model class with defaults, get/set/unset, per-attribute change events, previous values and silent updates.

JS Functions
Hard
40 min

6.Cache Async (Deduplicate Requests)

Memoize an async function so concurrent calls share one in-flight promise, results expire after a TTL and failures are not cached.

JS Functions
Medium
25 min

7.classnames

Build a CSS class string from strings, numbers, nested arrays and conditional objects.

JS Functions
Medium
20 min

8.Curry

Turn a function of n arguments into one that can be called with those arguments one or several at a time.

JS Functions
Medium
20 min

9.Data Selection

Implement a small query function over an array of records: filtering, multi-key stable sorting, pagination and field projection.

JS Functions
Medium
30 min

10.Debounce

Delay invoking a function until a burst of calls has stopped for a given wait time.

JS Functions
Medium
20 min

11.Deep Clone

Make a deep copy of a JSON-like value so that no nested object or array is shared with the original.

JS Functions
Medium
15 min

12.Deep Equal

Decide whether two JSON-like values are structurally equal, comparing nested objects and arrays by content.

JS Functions
Medium
20 min

13.Event Emitter

Implement an EventEmitter class with on, off and emit, the observer pattern behind Node's events module and DOM events.

JS Functions
Medium
20 min

14.Event Emitter II

Extend an event emitter with once, unsubscribe handles, bulk off and listener counts, with well-defined behaviour during emit.

JS Functions
Medium
25 min

15.Flatten

Flatten a nested array to a given depth, recursively or with an explicit stack.

JS Functions
Medium
20 min

16.Function.prototype.bind

Implement Function.prototype.bind with partial application and correct behaviour under new.

JS Functions
Medium
20 min

17.Get

Safely read a nested value from an object by a dot/bracket path, falling back to a default.

JS Functions
Medium
20 min

18.getElementsByClassName

Find every descendant element that has all of the given class names by walking the DOM tree yourself.

JS Functions
Medium
15 min

19.getElementsByTagName

Return every descendant element with a given tag name (or all of them for "*") by traversing the DOM tree.

JS Functions
Medium
15 min

20.Group By

Group the elements of an array into arrays keyed by the result of an iteratee.

JS Functions
Medium
15 min

21.JSON.stringify

Reimplement JSON.stringify: escaping, undefined and function handling, toJSON, wrapper objects, cycles and BigInt errors.

JS Functions
Hard
40 min

22.List Format

Format a list of names into a readable sentence with options for sorting, de-duplication and an "and N others" cutoff.

JS Functions
Medium
20 min

23.LRU Cache

Implement a fixed-capacity cache that evicts the least recently used entry, with O(1) get and set.

JS Functions
Medium
25 min

24.Map Async

Map over a list with an async callback, running every call in parallel and keeping the results in input order.

JS Functions
Medium
15 min

25.Map Async with Limit

Map over a list with an async callback while never running more than a given number of calls at once.

JS Functions
Hard
30 min

26.Memoize

Cache a function's results by argument so repeated calls with the same input skip the work.

JS Functions
Medium
15 min

27.Middlewares

Compose async middleware functions into one onion-style pipeline where each step can run code before and after next().

JS Functions
Medium
25 min

28.Promise.all

Implement Promise.all: resolve with every result in order, or reject on the first failure.

JS Functions
Medium
20 min

29.Promise.any

Implement Promise.any: fulfill with the first success, or reject with an AggregateError.

JS Functions
Medium
20 min

30.Promise Implementation

Build a Promises/A+-style MyPromise with then, catch, finally, chaining and thenable adoption.

JS Functions
Hard
45 min

31.Promise Pool

Build a concurrency-limited task queue: tasks can be added at any time and at most N run at once.

JS Functions
Hard
30 min

32.Promise Timeout

Wrap a promise so it rejects with a TimeoutError if it doesn't settle in time, without leaking timers.

JS Functions
Medium
15 min

33.Promisify

Convert a Node-style callback function into one that returns a promise.

JS Functions
Medium
15 min

34.Pub/Sub Store (Mini Redux)

Implement createStore with getState, dispatch and subscribe: the core of Redux in about 50 lines.

JS Functions
Medium
25 min

35.Retry with Backoff

Retry a failing async operation with exponential backoff and a predicate that decides which errors are worth retrying.

JS Functions
Medium
20 min

36.Signals (Fine-Grained Reactivity)

Implement createSignal, createEffect, createMemo, batch and untrack with automatic dependency tracking and glitch-free updates.

JS Functions
Hard
60 min

37.Spreadsheet Evaluator

Build a spreadsheet engine: parse cell formulas, evaluate references and ranges, recompute dependents on change and detect cycles.

JS Functions
Hard
60 min

38.Squash Object

Flatten a nested object into a single level whose keys are dot-separated paths.

JS Functions
Medium
20 min

39.Table of Contents

Build a nested table of contents from the h1–h6 headings in a document, generating unique anchor ids and rendering it as nested lists.

JS Functions
Hard
35 min

40.Throttle

Limit a function to at most one call per wait window, with leading and trailing calls.

JS Functions
Medium
20 min

41.Undo/Redo History

Implement an undoable value with past and future stacks, redo invalidation, no-op detection and a bounded history size.

JS Functions
Medium
20 min

42.Unique Array

Remove duplicate values from an array while keeping the first occurrence of each, in order.

JS Functions
Easy
10 min

43.Query String Parse and Stringify

Parse a URL query string into an object (with repeated keys as arrays) and serialise it back, handling encoding, + as space and malformed input.

JS Functions
Medium
25 min

44.Virtual DOM Diff (Keyed Children)

Patch the real DOM from an old and a new virtual tree, reusing nodes by type and key and moving keyed children instead of recreating them.

JS Functions
Hard
50 min

45.Virtual DOM: createElement and render

Implement h() to build virtual DOM nodes and render() to turn them into real DOM, with attributes, styles, events and function components.

JS Functions
Hard
35 min

46.How do you abort a web request using `AbortController` in JavaScript?

Cancelling fetch with signals, timeouts, AbortSignal.any and cleaning up in effects.

Quiz · JavaScript
Medium
6 min

47.What is async/await and how does it simplify asynchronous code?

Syntax over promises: sequential vs parallel awaits, error handling, top-level await and pitfalls.

Quiz · JavaScript
Medium
7 min

48.What are the common pitfalls of using the `this` keyword?

Lost receivers, callbacks, nested functions, arrow methods on objects and class field trade-offs.

Quiz · JavaScript
Easy
5 min

49.Explain the differences between CommonJS modules and ES modules in JavaScript

Static imports vs runtime require, live bindings, loading semantics, tree-shaking and interop in Node.

Quiz · JavaScript
Medium
8 min

50.How do you handle errors in asynchronous operations?

try/catch with await, .catch, unhandled rejections, fetch HTTP errors, aggregation and retries.

Quiz · JavaScript
Easy
7 min

51.What is the event loop? Explain the difference between the macrotask and microtask queues.

How JavaScript schedules callbacks, promises and rendering on a single thread.

Quiz · JavaScript
Medium
8 min

52.How do you handle errors using try...catch blocks?

How try/catch works with sync and async code, and how to catch errors usefully.

Quiz · JavaScript
Easy
5 min

53.How do you make an HTTP request using the Fetch API?

GET and POST with fetch, checking response.ok, timeouts and cancellation.

Quiz · JavaScript
Easy
6 min

54.How do you import and export modules in JavaScript?

Named, default, namespace, re-export and dynamic imports, and live bindings.

Quiz · JavaScript
Easy
5 min

55.What are the various data types in JavaScript?

The seven primitives plus objects, typeof quirks, and value vs reference semantics.

Quiz · JavaScript
Easy
5 min

56.What are modules and why are they useful?

Scope isolation, explicit dependencies, tree shaking and code splitting with ES modules.

Quiz · JavaScript
Easy
5 min

57.Explain the concept of lexical scoping

Scope decided by where code is written, the scope chain, and how it enables closures.

Quiz · JavaScript
Easy
5 min

58.Explain the Observer pattern and its use cases

Subjects notifying subscribers: event emitters, EventTarget, stores and their pitfalls.

Quiz · JavaScript
Medium
6 min

59.How is `Promise.all()` different from `Promise.allSettled()`?

Fail-fast vs wait-for-everything, result shapes, and where any and race fit in.

Quiz · JavaScript
Medium
5 min

60.Explain the different states of a Promise

Pending, fulfilled and rejected, what settled and resolved really mean, and why state is immutable.

Quiz · JavaScript
Medium
5 min

61.Explain the concept of scope in JavaScript

Global, module, function and block scope, the scope chain, shadowing and the temporal dead zone.

Quiz · JavaScript
Easy
6 min

62.What are Sets and Maps and how are they used?

Unique-value collections and keyed collections with any key type, plus new Set methods.

Quiz · JavaScript
Easy
5 min

63.How can you test asynchronous code in JavaScript?

Awaiting promises, asserting rejections, fake timers and waiting for UI updates.

Quiz · JavaScript
Medium
6 min

64.Explain the difference between unit testing, integration testing, and end-to-end testing

Scope, speed, confidence and cost of each level, with front-end examples.

Quiz · JavaScript
Medium
6 min

65.Explain the different ways the `this` keyword can be bound

Default, implicit, explicit and new binding, arrow functions, and the precedence between them.

Quiz · JavaScript
Medium
6 min

66.What are Promises and how do they work?

Promise objects, chaining, error propagation, microtask scheduling and Promise.withResolvers.

Quiz · JavaScript
Easy
7 min

67.What is the use of `Promise.all()`

Running independent async work in parallel, fail-fast semantics and concurrency limits.

Quiz · JavaScript
Easy
5 min

68.How do you write unit tests for JavaScript code?

Arrange-act-assert, testing behaviour not implementation, isolation and edge cases.

Quiz · JavaScript
Medium
6 min

69.Array.prototype.at

Implement Array.prototype.at, including negative indices and the spec's integer coercion rules.

JS Functions
Easy
10 min

70.Array.prototype.concat

Implement Array.prototype.concat, including sparse arrays and Symbol.isConcatSpreadable.

JS Functions
Easy
15 min

71.Async Queue with Priority

Run async tasks with a concurrency limit, starting higher-priority tasks first and keeping FIFO order within a priority.

JS Functions
Hard
35 min

72.Camel Case Keys

Deeply convert snake_case object keys from an API response into camelCase.

JS Functions
Medium
20 min

73.Cancellable Interval

Wrap setInterval so it returns a cancel function that stops future ticks.

JS Functions
Easy
5 min

74.Cancellable Timeout

Wrap setTimeout so it returns a cancel function instead of a timer id.

JS Functions
Easy
5 min

75.Chunk

Split an array into consecutive groups of a fixed size, with a shorter final group if needed.

JS Functions
Easy
10 min

76.Compose

Combine functions right to left into a single function, where each output feeds the next input.

JS Functions
Easy
10 min

77.Count By

Count how many elements of an array map to each key produced by an iteratee.

JS Functions
Easy
10 min

78.Curry II (with placeholders)

Curry a function so that arguments can be supplied in any order using a placeholder value.

JS Functions
Hard
30 min

79.Data Merging

Merge workout session records by user: sum durations and combine equipment lists without duplicates.

JS Functions
Medium
20 min

80.Debounce II

Debounce with leading, trailing and maxWait options, plus cancel and flush.

JS Functions
Hard
35 min

81.Deep Clone II

Deep clone values with circular references, shared references, Date, RegExp, Map, Set, symbols and prototypes.

JS Functions
Hard
35 min

82.Deep Map

Transform every leaf value in a nested object/array structure while preserving its shape.

JS Functions
Medium
20 min

83.Deep Merge

Recursively merge configuration objects without mutating the inputs, with clear rules for arrays and undefined.

JS Functions
Medium
25 min

84.Deep Omit

Remove the given keys from an object at every level of nesting, including inside arrays.

JS Functions
Medium
20 min

85.Dependency Injection Container

Build an IoC container with transient, singleton and scoped lifetimes, child scopes, overrides and circular-dependency detection.

JS Functions
Medium
35 min

86.Difference

Return the elements of an array that do not appear in any of the other given arrays.

JS Functions
Easy
10 min

87.Identical DOM Trees

Decide whether two DOM nodes are structurally identical: same tags, attributes, text and children, without using isEqualNode.

JS Functions
Medium
20 min

88.Feature Flag Evaluator

Evaluate feature flags with a kill switch, targeting rules and a percentage rollout that uses stable hashing so users keep their bucket.

JS Functions
Medium
30 min

89.Function.prototype.apply

Implement Function.prototype.apply, including array-like argument lists and argument validation.

JS Functions
Medium
15 min

90.Function.prototype.call

Implement Function.prototype.call without using call, apply or bind.

JS Functions
Medium
15 min

91.getElementsByStyle

Find descendant elements whose computed value for a CSS property equals a given value, normalising values like red vs #f00.

JS Functions
Medium
20 min

92.Has

Check whether an object has an own property at a nested path, even when the value is undefined.

JS Functions
Medium
15 min

93.HTML Serializer

Turn a plain-object element tree into pretty-printed, correctly escaped HTML with indentation and void elements.

JS Functions
Easy
20 min

94.instanceof

Re-implement the instanceof operator by walking the prototype chain.

JS Functions
Medium
15 min

95.Intersection

Return the unique values that appear in every one of the given arrays.

JS Functions
Medium
15 min

96.Is Empty

Decide whether a value is empty: no length, no size, or no own enumerable keys depending on its type.

JS Functions
Medium
15 min

97.jQuery Class Manipulation

Build a tiny $ wrapper with chainable addClass, removeClass, toggleClass and hasClass that work on every matched element.

JS Functions
Easy
15 min

98.jQuery CSS

Implement a $(selector).css() getter/setter that handles camelCase names, objects, automatic px units and removal.

JS Functions
Easy
15 min

99.JSON.parse (Lite)

Write a recursive-descent parser for JSON text that matches JSON.parse and throws SyntaxError on invalid input.

JS Functions
Hard
45 min

100.Make Counter

Use a closure to build independent counters that remember their own state between calls.

JS Functions
Easy
10 min

101.Max By

Return the element whose iteratee value is largest, skipping elements that produce no comparable value.

JS Functions
Easy
10 min

102.Memoize II (multiple arguments)

Memoize a function of any number of arguments with a collision-free cache keyed on every argument.

JS Functions
Medium
25 min

103.Min By

Return the element whose iteratee value is smallest, skipping elements that produce no comparable value.

JS Functions
Easy
10 min

104.new Operator

Re-implement the new operator: create the object, link the prototype, run the constructor.

JS Functions
Medium
15 min

105.Object.create

Implement Object.create, including null prototypes and property descriptors.

JS Functions
Easy
10 min

106.Observable

Build a minimal Observable with subscribe, unsubscribe, teardown, of/from creators and pipeable map and filter operators.

JS Functions
Hard
40 min

107.Omit

Create a shallow copy of an object without the listed keys.

JS Functions
Medium
10 min

108.Once

Wrap a function so that it runs at most once and later calls return the first result.

JS Functions
Easy
10 min

109.Partial

Pre-fill some of a function's arguments, with placeholders for positions supplied later.

JS Functions
Medium
15 min

110.Pick

Create a new object containing only the listed keys of a source object.

JS Functions
Easy
10 min

111.Pipe

Chain functions left to right so data flows through them in reading order.

JS Functions
Easy
10 min

112.Promise.allSettled

Implement Promise.allSettled: wait for every input and report each outcome in order.

JS Functions
Medium
15 min

113.Promise.race

Implement Promise.race: settle the same way as the first input to settle.

JS Functions
Easy
10 min

114.Promise.resolve

Implement Promise.resolve, including promise pass-through and thenable adoption.

JS Functions
Medium
15 min

115.Promise.withResolvers

Implement Promise.withResolvers to create a promise you can settle from outside its executor.

JS Functions
Easy
10 min

116.Promisify II

Extend promisify with a custom-implementation symbol, like Node's util.promisify.custom.

JS Functions
Medium
20 min

117.Range

Generate an array of numbers from start up to, but not including, end with an optional step.

JS Functions
Easy
10 min

118.Run Async Tasks in Series

Run a list of async functions one after another, passing each result to the next and stopping at the first failure.

JS Functions
Medium
15 min

119.Set

Write a value at a nested path, creating missing objects and arrays along the way.

JS Functions
Medium
25 min

120.setInterval with setTimeout

Re-implement setInterval and clearInterval using only chained setTimeout calls.

JS Functions
Medium
20 min

121.Sleep

Write a promise-based sleep(ms) and explain why it pauses an async function but not the thread.

JS Functions
Easy
5 min

122.Template Engine

Build a {{ }} interpolation engine with dotted paths, HTML escaping, raw {{{ }}} output, filters and a compile step.

JS Functions
Medium
30 min

123.Text Search Highlight

Wrap every case-insensitive match of the query words in <b> tags, merging overlapping and adjacent matches.

JS Functions
Medium
25 min

124.Type Utilities

Write reliable checks for JavaScript's primitive types, including the null and boxed-value traps.

JS Functions
Easy
15 min

125.Type Utilities II

Write type checks for non-primitive values: arrays, functions, objects and plain objects.

JS Functions
Medium
15 min

126.Union By

Merge several arrays into one list of unique elements, where uniqueness is decided by an iteratee.

JS Functions
Medium
15 min

127.How do you add, remove, and modify HTML elements using JavaScript?

createElement, append, replaceWith, remove, classList, fragments, templates and avoiding innerHTML XSS.

Quiz · JavaScript
Easy
6 min

128.What are the benefits of using currying and partial application?

Reuse, configuration, composition and point-free pipelines, plus the costs.

Quiz · JavaScript
Medium
5 min

129.Explain the concept of a callback function in asynchronous operations

Passing functions to be called later, error-first callbacks, callback hell and inversion of control.

Quiz · JavaScript
Easy
5 min

130.Can you describe the main difference between a .forEach loop and a .map() loop and why you would pick one versus the other?

To understand the differences between the two, let's look at what each function does.

Quiz · JavaScript
Medium
3 min

131.Can you give an example for destructuring an object or an array?

Destructuring is an expression available in ES6 which enables a succinct and convenient way to extract values of Objects or Arrays and place them into distinct

Quiz · JavaScript
Medium
3 min

132.Can you give an example of a curry function and why this syntax offers an advantage?

Currying is a pattern where a function with more than one parameter is broken into multiple functions that, when called in series, will accumulate all of the re

Quiz · JavaScript
Medium
3 min

133.Can you offer a use case for the new arrow => function syntax? How does this new syntax differ from other functions?

One obvious benefit of arrow functions is to simplify the syntax needed to create functions, without a need for the function keyword. The this within arrow func

Quiz · JavaScript
Medium
3 min

134.How do you reliably determine whether an object is empty?

Own keys vs enumerable keys, symbols, prototypes, null and non-plain objects.

Quiz · JavaScript
Easy
4 min

135.Explain the difference between classical inheritance and prototypal inheritance

Blueprint-copying classes vs live delegation to objects, and where JS classes fit.

Quiz · JavaScript
Easy
5 min

136.How can closures be used to create private variables?

The module/factory pattern for encapsulation, and how it compares to #private class fields.

Quiz · JavaScript
Easy
5 min

137.Explain the concept of code coverage and how it can be used to assess test quality

Line, branch and function coverage, what they miss, and mutation testing.

Quiz · JavaScript
Medium
5 min

138.What is the Command pattern and how is it used?

Encapsulating actions as objects for undo/redo, queues, macros and keyboard shortcuts.

Quiz · JavaScript
Medium
6 min

139.Create a for loop that iterates up to 100 while outputting **"fizz"** at multiples of 3, **"buzz"** at multiples of 5 and **"fizzbuzz"** at multiples of 3 and 5.

Check out this version of FizzBuzz by Paul Irish.

Quiz · JavaScript
Medium
3 min

140.Provide some examples of how currying and partial application can be used

Practical uses: event handlers, loggers, validators, API clients and pipelines.

Quiz · JavaScript
Easy
6 min

141.How do currying and partial application differ from each other?

Unary chains versus fixing some arguments once, with implementations of both.

Quiz · JavaScript
Medium
5 min

142.How can you create custom error objects?

Subclassing Error with name, code and cause, and the instanceof caveats.

Quiz · JavaScript
Medium
6 min

143.What is the Decorator pattern and how is it used?

Wrapping objects or functions to add behaviour, including higher-order functions and TC39 decorators.

Quiz · JavaScript
Medium
6 min

144.Describe event bubbling.

When an event triggers on a DOM element, it will attempt to handle the event if there is a listener attached, then the event is bubbled up to its parent and the

Quiz · JavaScript
Medium
3 min

145.Describe event capturing in JavaScript and browsers

The top-down phase of DOM event propagation and when listening in it is useful.

Quiz · JavaScript
Easy
5 min

146.What are design patterns and why are they useful?

Reusable solutions to recurring design problems and a shared vocabulary for teams.

Quiz · JavaScript
Easy
5 min

147.Difference between document load event and document DOMContentLoaded event?

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes

Quiz · JavaScript
Medium
3 min

148.Difference between: function Person(){}, var person = Person(), and var person = new Person()?

This question is pretty vague. My best guess at its intention is that it is asking about constructors in JavaScript. Technically speaking, function Person(){} i

Quiz · JavaScript
Medium
3 min

149.Explain the concept of error propagation in JavaScript

How errors unwind the call stack, flow through promise chains and reach global handlers.

Quiz · JavaScript
Medium
6 min

150.ES6 Template Literals offer a lot of flexibility in generating strings, can you give an example?

Template literals help make it simple to do string interpolation, or to include variables in a string. Before ES2015, it was common to do something like this:

Quiz · JavaScript
Medium
3 min

151.What are event listeners and how are they used?

addEventListener options (capture, once, passive, signal), removal and memory hygiene.

Quiz · JavaScript
Easy
5 min

152.Explain the event phases in a browser

Capture, target and bubble phases, eventPhase values, and how shadow DOM retargeting fits in.

Quiz · JavaScript
Medium
6 min

153.Explain Ajax in as much detail as possible.

Ajax (asynchronous JavaScript and XML) is a set of web development techniques using many web technologies on the client side to create asynchronous web applicat

Quiz · JavaScript
Medium
3 min

154.Explain event delegation

Event delegation is a technique involving adding event listeners to a parent element instead of adding them to the descendant elements. The listener will fire w

Quiz · JavaScript
Medium
3 min

155.Explain Function.prototype.bind.

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any pro

Quiz · JavaScript
Medium
3 min

156.Explain "hoisting".

Hoisting is a term used to explain the behavior of variable declarations in your code. Variables declared or initialized with the var keyword will have their de

Quiz · JavaScript
Medium
3 min

157.Explain how JSONP works (and how it's not really Ajax).

JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers because Ajax requests from the current page to a cross-o

Quiz · JavaScript
Medium
3 min

158.Explain how prototypal inheritance works

All JavaScript objects have a proto property with the exception of objects created with Object.create(null), that is a reference to another object, which is cal

Quiz · JavaScript
Medium
3 min

159.Explain how this works in JavaScript

There's no simple explanation for this; it is one of the most confusing concepts in JavaScript. A hand-wavey explanation is that the value of this depends on ho

Quiz · JavaScript
Medium
3 min

160.Explain the difference between mutable and immutable objects.

Immutability is a core principle in functional programming, and has lots to offer to object-oriented programs as well. A mutable object is an object whose state

Quiz · JavaScript
Medium
7 min

161.Explain the difference between synchronous and asynchronous functions.

Synchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. In this

Quiz · JavaScript
Medium
3 min

162.Explain the differences on the usage of foo between function foo() {} and var foo = function() {}

The former is a function declaration while the latter is a function expression. The key difference is that function declarations have its body hoisted but the b

Quiz · JavaScript
Medium
3 min

163.Explain the same-origin policy with regards to JavaScript.

The same-origin policy restricts how a document or script from one origin can interact with resources from another origin. Two URLs have the same origin when th

Quiz · JavaScript
Medium
3 min

164.Explain what a single page app is and how to make one SEO-friendly.

The below is taken from the awesome Grab Front End Guide, which coincidentally, is written by me!

Quiz · JavaScript
Medium
4 min

165.Explain why the following doesn't work as an IIFE: function foo(){ }();. What needs to be changed to properly make it an IIFE?

IIFE stands for Immediately Invoked Function Expressions. The JavaScript parser reads function foo(){ }(); as function foo(){ } and ();, where the former is a f

Quiz · JavaScript
Medium
3 min

166.What is the Factory pattern and how is it used?

Creating objects through a function that hides construction details.

Quiz · JavaScript
Medium
5 min

167.Have you ever used JavaScript templating? If so, what libraries have you used?

Yes. Handlebars, Underscore, Lodash, AngularJS, and JSX. I disliked templating in AngularJS because it made heavy use of strings in the directives and typos wou

Quiz · JavaScript
Medium
3 min

168.How can you share code between files?

This depends on the JavaScript environment.

Quiz · JavaScript
Medium
3 min

169.How do you organize your code? (module pattern, classical inheritance?)

In the past, I've used Backbone for my models which encourages a more OOP approach, creating Backbone models and attaching methods to them.

Quiz · JavaScript
Medium
3 min

170.How does JavaScript garbage collection work?

Reachability, mark-and-sweep, generational collection and how front-end apps leak memory.

Quiz · JavaScript
Hard
7 min

171.Explain the concept of inheritance in ES2015 classes

extends, super, constructor rules, method overriding, statics and private fields in subclasses.

Quiz · JavaScript
Easy
6 min

172.What is the difference between innerHTML and textContent?

How markup parsing, text nodes and innerText differ, and why textContent is the safe default.

Quiz · JavaScript
Medium
5 min

173.What is the Intl namespace object for?

Locale-aware formatting of numbers, dates, plurals, lists, collation and segmentation.

Quiz · JavaScript
Medium
6 min

174.What are iterators and generators in JavaScript and what are they used for?

The iteration protocols, function*, lazy sequences, async iteration and iterator helpers.

Quiz · JavaScript
Hard
8 min

175.What are the different types of errors in JavaScript?

Built-in Error subclasses, DOMException, and useful ways to categorise failures.

Quiz · JavaScript
Medium
5 min

176.What are some best practices for writing maintainable and effective tests in JavaScript?

Behaviour-focused, deterministic, readable tests that survive refactors.

Quiz · JavaScript
Medium
6 min

177.Make this work:

Make this work:

Quiz · JavaScript
Medium
3 min

178.How do you manipulate CSS styles using JavaScript?

Classes, custom properties, inline styles, computed styles and constructable stylesheets.

Quiz · JavaScript
Easy
5 min

179.What are the differences between `Map`/`Set` and `WeakMap`/`WeakSet` in JavaScript?

Weakly held keys, garbage collection, non-iterability, and real use cases like caches and private data.

Quiz · JavaScript
Easy
6 min

180.What is the difference between a `Map` object and a plain object in JavaScript?

Key types, ordering, size, prototype pitfalls, performance and serialisation compared.

Quiz · JavaScript
Easy
5 min

181.What are mocks and stubs and how are they used in testing?

Test doubles: stubs, mocks, spies and fakes, plus network mocking with MSW.

Quiz · JavaScript
Hard
6 min

182.What is the Module pattern and how does it help with encapsulation?

IIFE closures, revealing module, ES modules and private class fields for encapsulation.

Quiz · JavaScript
Medium
5 min

183.What is the difference between `mouseenter` and `mouseover` event in JavaScript and browsers?

Why mouseenter does not bubble or fire for children, and when each is the right choice.

Quiz · JavaScript
Easy
4 min

184.What are JavaScript object getters and setters for?

Computed properties, validation and encapsulation with get/set, plus their performance and debugging trade-offs.

Quiz · JavaScript
Medium
5 min

185.Other Answers

- https://github.com/sudheerj/javascript-interview-questions

Quiz · JavaScript
Medium
3 min

186.Explain the concept of partial application

Fixing some arguments of a function up front to create a more specific function.

Quiz · JavaScript
Medium
5 min

187.What are the potential pitfalls of using closures?

Loop capture bugs, stale closures in React, retained memory and per-instance function costs.

Quiz · JavaScript
Medium
6 min

188.What are some popular JavaScript testing frameworks?

Vitest, Jest, node:test, Testing Library, Playwright, Cypress and how they fit together.

Quiz · JavaScript
Easy
5 min

189.How do you prevent the default behavior of an event?

preventDefault, cancelable events, passive listeners and when not to block defaults.

Quiz · JavaScript
Easy
4 min

190.What is the difference between `event.preventDefault()` and `event.stopPropagation()`?

Cancelling the browser action vs stopping the event travelling, plus stopImmediatePropagation.

Quiz · JavaScript
Medium
5 min

191.What are JavaScript object property flags and descriptors?

writable, enumerable, configurable, accessor descriptors and how freeze/seal build on them.

Quiz · JavaScript
Hard
7 min

192.Explain the concept of the Prototype pattern

Creating objects from existing ones: Object.create, prototype sharing and cloning.

Quiz · JavaScript
Easy
5 min

193.What is the purpose of the finally block?

Cleanup that runs on every exit path, Promise.finally, override gotchas and using declarations.

Quiz · JavaScript
Easy
4 min

194.What is the purpose of the `new` keyword?

The four steps new performs, return-value rules, new.target and what cannot be constructed.

Quiz · JavaScript
Easy
5 min

195.Explain the difference between `document.querySelector()` and `document.getElementById()`

Selector power vs a direct id lookup, scoping, live vs static collections and escaping.

Quiz · JavaScript
Easy
4 min

196.How do you get the query string values of the current page in JavaScript?

Reading and updating query parameters safely with URLSearchParams and URL.

Quiz · JavaScript
Easy
4 min

197.How do Sets and Maps handle equality checks for objects?

SameValueZero and reference identity for object keys, and how to dedupe by value.

Quiz · JavaScript
Easy
5 min

198.What is the difference between `setTimeout()`, `setImmediate()`, and `process.nextTick()`?

Where each callback lands in the Node.js event loop, and the browser equivalents.

Quiz · JavaScript
Medium
6 min

199.Explain the concept of the Singleton pattern

One shared instance, why ES modules already give you one, and the testing downsides.

Quiz · JavaScript
Easy
5 min

200.Explain the concept of the Strategy pattern

Swapping interchangeable algorithms behind one interface, often as a map of functions.

Quiz · JavaScript
Medium
5 min

201.Explain the concept of test-driven development (TDD)

Red-green-refactor, its benefits, costs and where it fits in front-end work.

Quiz · JavaScript
Medium
5 min

202.Explain the concept of `this` binding in event handlers

this as currentTarget in listeners, arrows and bind, removing bound listeners and handleEvent objects.

Quiz · JavaScript
Easy
5 min

203.What are the different types of testing in software development?

Functional and non-functional test types and how they fit a front-end strategy.

Quiz · JavaScript
Medium
6 min

204.What are the various ways to create objects in JavaScript?

Object literals, constructors, classes, Object.create, factories and structuredClone compared.

Quiz · JavaScript
Easy
5 min

205.What advantage is there for using the arrow syntax for a method in a constructor?

The main advantage of using an arrow function as a method inside a constructor is that the value of this gets set at the time of the function creation and can't

Quiz · JavaScript
Medium
3 min

206.What are JavaScript polyfills for?

Filling missing APIs in older environments, how polyfills differ from transpilation, and their costs.

Quiz · JavaScript
Hard
6 min

207.What are proxies in JavaScript used for?

Intercepting object operations with traps and Reflect: validation, reactivity, logging and their limits.

Quiz · JavaScript
Hard
8 min

208.What are server-sent events?

One-way streaming over HTTP with EventSource: format, reconnection, limits and alternatives.

Quiz · JavaScript
Hard
7 min

209.What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?

Some examples of languages that compile to JavaScript include CoffeeScript, Elm, ClojureScript, PureScript, and TypeScript.

Quiz · JavaScript
Medium
3 min

210.What are `Symbol`s used for in JavaScript?

Unique property keys, the global registry, and well-known symbols that hook into language behaviour.

Quiz · JavaScript
Medium
6 min

211.What are the advantages and disadvantages of using Ajax?

- Better interactivity. New content from the server can be changed dynamically without the need to reload the entire page.

Quiz · JavaScript
Medium
3 min

212.What are the benefits of using spread syntax and how is it different from rest syntax?

ES6's spread syntax is very useful when coding in a functional paradigm as we can easily create copies of arrays or objects without resorting to Object.create,

Quiz · JavaScript
Medium
3 min

213.What are the differences between ES6 class and ES5 function constructors?

Let's first look at an example of each:

Quiz · JavaScript
Medium
3 min

214.What are the differences between variables created using let, var or const?

Variables declared using the var keyword are scoped to the function in which they are created, or if created outside of any function, to the global object. let

Quiz · JavaScript
Medium
3 min

215.What are the pros and cons of using Promises instead of callbacks?

- Avoid callback hell which can be unreadable.

Quiz · JavaScript
Medium
3 min

216.What are workers in JavaScript used for?

Dedicated, shared and service workers: off-main-thread work, messaging, transferables and limits.

Quiz · JavaScript
Hard
7 min

217.What do you think of AMD vs CommonJS?

Both are ways to implement a module system, which was not natively present in JavaScript until ES2015 came along. CommonJS is synchronous while AMD (Asynchronou

Quiz · JavaScript
Medium
3 min

218.What is a closure, and how/why would you use one?

A closure is the combination of a function and the lexical environment within which that function was declared. The word "lexical" refers to the fact that lexic

Quiz · JavaScript
Medium
3 min

219.What is the definition of a higher-order function?

A higher-order function is any function that takes one or more functions as arguments, which it uses to operate on some data, and/or returns a function as a res

Quiz · JavaScript
Medium
3 min

220.What is the difference between == and ===?

== is the abstract equality operator while === is the strict equality operator. The == operator will compare for equality after doing any necessary type convers

Quiz · JavaScript
Medium
3 min

221.What is the DOM and how is it structured?

The live tree of nodes the browser builds from HTML, node types, and how it relates to rendering.

Quiz · JavaScript
Easy
5 min

222.What is the extent of your experience with Promises and/or their polyfills?

Possess working knowledge of it. A promise is an object that may produce a single value sometime in the future: either a resolved value or a reason that it's no

Quiz · JavaScript
Medium
3 min

223.What is "use strict";? What are the advantages and disadvantages to using it?

'use strict' is a statement used to enable strict mode to entire scripts or individual functions. Strict mode is a way to opt into a restricted variant of JavaS

Quiz · JavaScript
Medium
3 min

224.What language constructions do you use for iterating over object properties and array items?

- for-in loops - for (var property in obj) { console.log(property); }. However, this will also iterate through its inherited properties, and you will add an obj

Quiz · JavaScript
Medium
4 min

225.What's a typical use case for anonymous functions?

They can be used in IIFEs to encapsulate some code within a local scope so that variables declared in it do not leak to the global scope.

Quiz · JavaScript
Medium
3 min

226.What's the difference between a variable that is: null, undefined or undeclared? How would you go about checking for any of these states?

Undeclared variables are created when you assign a value to an identifier that is not previously created using var, let or const. Undeclared variables will be d

Quiz · JavaScript
Medium
3 min

227.What's the difference between an "attribute" and a "property"?

Attributes are defined on the HTML markup but properties are defined on the DOM. To illustrate the difference, imagine we have this text field in our HTML: <inp

Quiz · JavaScript
Medium
3 min

228.What's the difference between .call and .apply?

Both .call and .apply are used to invoke functions and the first parameter will be used as the value of this within the function. However, .call takes in comma-

Quiz · JavaScript
Medium
3 min

229.What's the difference between feature detection, feature inference, and using the UA string?

Feature detection involves working out whether a browser supports a certain block of code, and running different code depending on whether it does (or doesn't),

Quiz · JavaScript
Medium
3 min

230.What's the difference between host objects and native objects?

Native objects are objects that are part of the JavaScript language defined by the ECMAScript specification, such as String, Math, RegExp, Object, Function, etc

Quiz · JavaScript
Medium
3 min

231.What tools and techniques do you use for debugging JavaScript code?

- Good old console.log debugging

Quiz · JavaScript
Medium
3 min

232.When would you use document.write()?

document.write() writes a string of text to a document stream opened by document.open(). When document.write() is executed after the page has loaded, it will ca

Quiz · JavaScript
Medium
3 min

233.Why is extending built-in JavaScript objects not a good idea?

Extending a built-in/native JavaScript object means adding properties/functions to its prototype. While this may seem like a good idea at first, it is dangerous

Quiz · JavaScript
Medium
3 min

234.Why is it called a Ternary expression, what does the word "Ternary" indicate?

"Ternary" indicates three, and a ternary expression accepts three operands, the test condition, the "then" expression and the "else" expression. Ternary express

Quiz · JavaScript
Medium
3 min

235.Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?

Every script has access to the global scope, and if everyone uses the global namespace to define their variables, collisions will likely occur. Use the module p

Quiz · JavaScript
Medium
3 min

236.Why might you want to create static class members?

Static class members (properties/methods) are not tied to a specific instance of a class and have the same value regardless of which instance is referring to it

Quiz · JavaScript
Medium
3 min

237.Why would you use something like the load event? Does this event have disadvantages? Do you know any alternatives, and why would you use those?

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts,

Quiz · JavaScript
Medium
3 min

238.What are the differences between `XMLHttpRequest` and `fetch()` in JavaScript and browsers?

Promise-based fetch versus event-based XHR: errors, cancellation, streaming, progress and cookies.

Quiz · JavaScript
Easy
6 min

239.Array.prototype.square

Add a square() method to every array that returns a new array of squared values.

JS Functions
Easy
5 min

240.Clamp

Restrict a number to an inclusive range between a lower and an upper bound.

JS Functions
Easy
5 min

241.Compact

Return a new array with every falsy value removed.

JS Functions
Easy
5 min

242.Drop Right While

Drop trailing elements of an array for as long as a predicate holds, scanning from the end.

JS Functions
Easy
10 min

243.Drop While

Drop leading elements of an array for as long as a predicate holds, then keep the rest.

JS Functions
Easy
10 min

244.Fill

Overwrite a range of an array with a value, supporting negative start and end indices.

JS Functions
Easy
10 min

245.Find Index

Return the index of the first element that satisfies a predicate, starting from an optional index.

JS Functions
Easy
10 min

246.Find Last Index

Return the index of the last element that satisfies a predicate, searching backwards from an optional index.

JS Functions
Easy
10 min

247.From Pairs

Build an object from an array of [key, value] pairs, the inverse of Object.entries.

JS Functions
Easy
5 min

248.In Range

Check whether a number lies in a half-open range, with an optional start and swapped bounds.

JS Functions
Easy
10 min

249.Mean

Compute the arithmetic mean of an array of numbers, returning NaN for an empty array.

JS Functions
Easy
5 min

250.Number of Arguments

Return how many arguments a function was called with, and explain arguments vs rest vs Function.length.

JS Functions
Easy
5 min

251.Promise.reject

Implement Promise.reject and explain why it never unwraps promises or thenables.

JS Functions
Easy
5 min

252.Range Right

Generate the same numbers as range(start, end, step) but in descending order of generation.

JS Functions
Easy
10 min

253.Size

Return the size of a collection: length for arrays and strings, size for Map and Set, key count for objects.

JS Functions
Easy
10 min

254.String Repeat and Pad

Implement repeat, padStart and padEnd without the built-in string methods, matching their edge-case behaviour.

JS Functions
Easy
15 min

255.How do you convert a Set to an array in JavaScript?

Spread, Array.from and when you might not need to convert at all.

Quiz · JavaScript
Easy
4 min

256.How do you create a constructor function?

Writing a constructor, putting methods on the prototype, guarding against missing new, and the class equivalent.

Quiz · JavaScript
Easy
4 min

257.What are some tools that can be used for JavaScript testing?

The wider testing toolbox: runners, DOM utilities, mocking, browsers, visual, a11y and static checks.

Quiz · JavaScript
Easy
5 min

258.What are the metadata fields of a module?

import.meta.url, import.meta.resolve, host-specific fields and package.json module metadata.

Quiz · JavaScript
Medium
5 min

259.What is `Object.preventExtensions()` for?

Blocking new properties, and how it compares to Object.seal and Object.freeze.

Quiz · JavaScript
Medium
4 min

More interview questions

React Interview QuestionsTypeScript Interview QuestionsCSS Interview QuestionsHTML Interview QuestionsSenior Frontend Interview QuestionsLead Frontend Engineer Interview QuestionsQuestions by topic