ES6 interview questions.
ES6 (ES2015) and the versions after it changed how JavaScript is written, and interviews still ask about each feature: what it does, how it differs from the old way, and when it surprises people. These questions have you use classes, Map and Set, symbols, iterators, generators and modules in real code, with written answers to the concept questions below them.
3 of these questions have free answers; the rest are in Pro. Updated .
104
questions
- Easy
- 38
- Medium
- 44
- Hard
- 22
What interviewers look for
- You know how let, const and arrow functions differ from var and regular functions, including this.
- You use destructuring, spread and rest, and know that spread copies one level deep.
- You choose Map or Set over a plain object or array when keys or uniqueness call for it.
- You can make an object iterable and explain what a generator gives you.
Concept questions, answered
The definitions and comparisons interviewers open with. Free to read, each with a full answer and examples.
What are the most important ES6 features in JavaScript?
ES6, officially ECMAScript 2015, was the largest update to JavaScript. Its most important features are let and const, arrow functions, classes, template literals, destructuring, spread and rest syntax, default parameters, ES modules with import and export, promises, Map and Set, symbols, and iterators with generators and for...of. Together they replaced most ES5 workarounds such as var hoisting, self = this and IIFE modules.
What is the difference between var, let and const?
var is function scoped, can be redeclared and is hoisted with the value undefined. let and const are block scoped, cannot be redeclared in the same scope and cannot be used before their declaration. let can be reassigned, while const cannot be rebound. Use const by default, let when you must reassign, and avoid var.
How are arrow functions different from regular functions?
Arrow functions are a shorter syntax with different behaviour. They have no this, arguments or super of their own and use those of the surrounding code. They cannot be called with new, have no prototype, and cannot be generators. Regular functions get their own this from how they are called.
What is destructuring in JavaScript?
Destructuring is syntax that unpacks values from an array or properties from an object into separate variables in one statement. Instead of reading user.name and user.age line by line, you write const { name, age } = user. It also works in function parameters, loops and catch clauses.
What is the difference between the spread and rest operators?
Spread and rest both use ..., but they do opposite jobs. Spread expands an array, string or object into separate values where you use it. Rest collects the remaining values into one array or object where you declare them, in function parameters or destructuring. Position decides which one you have.
ES6 classes vs ES5 constructor functions: what changed?
ES6 classes use the same prototype system as ES5 constructor functions, but they are not just new syntax. A class must be called with new, runs in strict mode, has non-enumerable methods and is in the temporal dead zone until declared. extends sets up inheritance correctly, even for built-ins like Array and Error, and classes add super, private #fields and static blocks.
Map vs object and Set vs array in JavaScript
Use a Map when you need a dictionary with arbitrary keys, a reliable size and frequent additions and removals. Use a plain object for fixed-shape records and JSON. Use a Set when you need unique values and fast membership checks, and an array when order, indexes or array methods matter.
What is a Symbol in JavaScript used for?
A Symbol is a primitive value that is guaranteed to be unique, created by calling Symbol(). Its main use is as an object property key that can never collide with any other key, so libraries can add properties without clashing with yours. Built-in well-known symbols such as Symbol.iterator let objects plug into language features.
What are generators in JavaScript?
A generator is a function declared with function* that can pause at each yield and resume later. Calling it does not run the body: it returns an iterator, and each next() call runs until the next yield. Generators produce values lazily, one at a time, and can receive values back.
What are WeakMap and WeakSet used for?
WeakMap and WeakSet store objects without preventing them from being garbage collected. A WeakMap links extra data to an object key, and a WeakSet marks objects as members. When nothing else references the object, the entry disappears automatically, so they are used for metadata, caches and private data that must not leak memory.
ES modules vs CommonJS: what is the difference?
ES modules (ESM) use import and export, are analysed before the code runs, and export live bindings. CommonJS (CJS) uses require() and module.exports, runs synchronously, and exports a value at the time of the call. ESM is the language standard for browsers and Node. CommonJS is the older Node format.
What do optional chaining (?.) and nullish coalescing (??) do?
Optional chaining (?.) reads a property, index or method only if the value before it is not null or undefined; otherwise the whole expression returns undefined instead of throwing. Nullish coalescing (??) returns its right side only when the left side is null or undefined. Together, user?.address?.city ?? "Unknown" reads a nested value safely and supplies a default.
Easy38
- Remove duplicate items from an arrayImplement unique(array, getKey). It returns a new array without duplicates, keeping the first occurrence of each item in…
- Predict what
thisrefers to in methods, detached calls, arrows,bindandnewThe snippet below runs in strict mode (as all modules and classes do). name(value) turns whatever this is into a… - Fix the
varloop closure bug three waysThis function should log 0, 1, 2, …, n - 1, but it doesn't: - Predict hoisting and TDZ results for functions,
var,let,constandclassFreeRead each snippet and write down exactly what it logs, without running it. When a line throws, the snippet logs the… - Implement a deep
map()over nested data, with paths and cyclesImplement deepMap(value, fn), which returns a copy of nested data with every leaf value replaced by fn(leaf, path). - Predict
Map,Setand object key behaviour"What is the difference between a Map and an object?" is one of the most searched JavaScript questions. Show you know it… - Predict function results:
arguments, default parameters, rest,lengthand arrows"JavaScript interview questions on functions" usually means small snippets about parameters, arguments and arrow… - Predict prototype and class results: inheritance, shadowing, class fields and
super"JavaScript interview questions on prototypes and classes" usually mean snippets like these. Predict what each one logs,… - Predict ES6 results: destructuring defaults, spread, optional chaining and
??versus||Modern syntax questions are interview favourites, especially "what is the difference between ?? and ||?". Predict what… - Predict generator results:
yield,next(value),return,throwandyield*Generators come up in interviews as "what does this log?" puzzles, and they are the base of iterators, async iteration… - Predict getter, setter and property descriptor results:
defineProperty,freezeandseal"What is the difference between Object.freeze and Object.seal?" and "how do getters and setters work?" are asked in… - Implement lodash-style array helpers:
compact,difference,intersection,fill,fromPairs,dropWhileandfindLastIndexSmall lodash helpers are a common warm-up: each one is a few lines, and the interviewer watches how you handle indices,… - Model a school with classes: inheritance, private fields, validated setters, a static id counter and overrides"Model this domain with classes" is a common first-round task: it checks extends and super, real encapsulation with…
- Write
Object.,entries Object.andfromEntries Object.polyfills: getters, symbols and own enumerable keysObject helpers look trivial until the interviewer asks which keys they copy. Implement three functions that behave like…assign - Write
Array.andfrom Array.polyfills: iterables, array-likes andof mapFnArray.from turns two very different kinds of input into arrays: iterables (anything with Symbol.iterator: strings, Set,… - Make a
Rangeclass and a linked list iterable withSymbol.: spread,iterator for...ofand early exitAny object can work with spread, for...of, destructuring and Array.from if it implements the iteration protocol. Build… - Flatten a nested array level by level (shallow values first) and implement
flatMapThe usual flatten question (question 8) walks the array depth first, so [1, [2], 3] becomes [1, 2, 3]. This variant,… - Build chainable APIs: a
CarwithaddSpeed()., and a proxy that records any method chain"Make these calls chain" has been reported in public interview write-ups in two forms: a class whose methods chain, like…minus() - Improve a slow filter: remove items that match any key/value exclude in linear timeYou are given a product list and a list of excludes, and this working but slow function:
- Build a lazy nested list iterator with
hasNext()andnext()that also accepts sets and generatorsWrite a class that walks a nested list such as [1, [2, [3, 4]], 5] one value at a time. The interviewer usually starts… - Build an ASCII canvas: draw lettered rectangles in z-order, move them and print the resultThis multi-step phone-screen task has been reported in public interview write-ups. You draw rectangles on a text canvas,…
- Build a stack that can delete any element in O(1) with a doubly linked listA stack normally removes only its top item. This one must also remove any item in O(1), which comes up when, for…
- Implement DOMStore, a map keyed by DOM nodes, without Map, WeakMap or SetBefore Map existed, libraries that stored data per element (event handlers, cached measurements, component instances)…
- Predict property-descriptor results: getters and setters through spread,
Object.,assign JSON.,stringify structuredCloneandObject.Getters are everywhere in real code: computed fields on models, class accessors, lazy config. The moment such an object…freeze - Polyfill
Array., includingprototype. concat Symbol.concat looks trivial, but it follows a precise rule about which values it spreads, it keeps holes, and objects can opt…isConcatSpreadable - Invert an object, collecting duplicate values into arraysInverting an object swaps keys and values: { en: "English", fr: "French" } becomes { English: "en", French: "fr" }. When…
- Join two arrays of records by idA page often loads two lists that describe the same things: users from one endpoint and their stats from another. Write…
- Predict
typeofandinstanceofresults:null, functions, classes, wrapper objects andSymbol."How do you check the type of a value?" sounds simple until the follow-ups arrive: typeof null, wrapper objects, objects…hasInstance - Predict property order and enumeration: integer-like keys,
for...in, symbols andObject.Code that renders object keys, builds query strings or compares snapshots depends on property order, and interviewers…entries - Predict
Symbol.,toPrimitive valueOfandtoStringcalls in+, template literals, comparisons andString()When an object meets an operator, JavaScript has to turn it into a primitive, and which method it calls depends on the… - Predict iterator protocol results: spreading a generator twice, early exits calling
return(), and destructuringSpread, for...of, destructuring, Array.from and Promise.all all speak the same iterator protocol, and you can watch them… - Predict
NaN,-0andObject.results acrossis includes,indexOf,Set,MapandsortNaN and -0 are the two values where JavaScript's equality algorithms disagree, which makes them a favourite for… - Predict tagged template results: the strings array,
raw, interpolated values and call-site cachingTagged templates power styled-components, GraphQL gql, String.raw and safe HTML builders, so interviewers ask how the… - Predict class results: static inheritance, private fields,
#x in obj, accessors and methods passed as callbacksModern class features (static fields, #private members, accessors and arrow fields) each come with a rule that surprises… - Predict quick-fire results: a detached method, a shadowed
let, a shallowObject.,freeze Promise.andresolve(fn) -0A JavaScript round often opens with short snippets and the question "what does this log?". This set has been reported in… - Bind an object property to an input both ways, without a frameworkVue's v-model and Angular's [(ngModel)] keep a piece of state and a form field in sync in both directions. Build the…
- Write two generators: walk an array in circular jumps, and yield factorials as BigIntGenerators can pause, hand back a value, and receive one on the way back in. Write two of them.
- Build an array iterator with
next(),done(),peek(),reset()andfor...ofsupportInterviewers often open with a small helper that walks an array one item at a time, then ask how it relates to…
Medium44
- Implement deep clone with circular references,
Map,Set, andDateImplement deepClone(value). It returns a copy where every nested object is new, so changing the copy never changes the… - Implement an EventEmitter with
on,off,emit, andonceImplement an EventEmitter class, similar to Node's: - Implement an
EventTarget-style custom event systemThe DOM's EventTarget behaves differently from a Node-style emitter. Implement a small version of it without using the… - Implement an asynchronous task runner with configurable concurrencyImplement a TaskRunner class. Unlike a pool over a fixed list, tasks can be added at any time, and the concurrency can…
- Implement a queue supporting pause, resume, and clearImplement a TaskQueue class that runs async tasks in order with a concurrency limit, and can be paused, resumed and…
- Paginate an API with an async generator that cleans up on early
breakA cursor-paginated API is easiest to consume as a stream of items: for await (const user of paginate(fetchPage)) { ...… - Stream NDJSON from
fetchand handle rows split across chunksAn export endpoint returns 200,000 rows as NDJSON: one JSON object per line. Waiting for the whole body before showing… - Implement
URLSearchParamsfrom scratchImplement a class MySearchParams that behaves like the browser's URLSearchParams for the common cases. Do not use… - Build a small Zod-style schema validatorLibraries such as Zod validate API responses and form data against a schema written in code. Build a small version: an…
- Build a time-travel key-value map that answers "what was the value at time t?"Feature flags, document versions and price histories all need "the value as of a moment". Implement a class HistoryMap.
- Build an in-memory key-value store with nested transactionsForm editors with "Cancel", game state with "undo this move" and optimistic UI all need transactions. Implement…
- Write tagged template literals: an escaping
htmltag,dedentandString.Tagged templates power lit-html, styled-components, GraphQL's gql and safe SQL builders. Interviewers ask how they work…raw - Implement a lazy
zip()andzipLongest()that close unfinished iteratorszip pairs up items from several sequences: zip([1, 2], ["a", "b"]) gives [1, "a"], then [2, "b"]. The array version is a… - Build a Backbone-style
Modelwithget,set,unsetand change eventsBefore React, a Backbone Model was how many apps held state: an object of attributes that tells listeners when something… - Implement a complete
isEqual(): Dates, RegExps, Maps, Sets, typed arrays, prototypes and cyclesQuestion 18 compares nested arrays and plain objects. Real data also holds dates, regular expressions, Maps, Sets,… - Remove circular references:
decycle()andretrocycle()with$refpaths, plusremoveCycles()JSON.stringify throws TypeError: Converting circular structure to JSON as soon as an object refers back to itself, which… - Build a
co()-style generator runner: await yielded promises, throw rejections back in and accumulate resultsBefore async/await existed, libraries like co gave the same feel with generators: you yield a promise, a runner waits… - Build async iterator helpers
map,filter,takeandtoArraythat clean up withreturn()Paginated APIs, ReadableStreams and WebSocket messages can all be consumed as async iterables. Helpers like map and take… - Build music player analytics: top songs by unique listeners and each user's recently played songsA music player sends a play event every time someone starts a song. The product team wants two things: a chart of songs…
- Build a CancellablePromise: cancel(), onCancel cleanup and cancellation through chains"How do you cancel a promise?" The short answer is that you cannot: a native promise has no cancel method, and once the…
- Polyfill
DisposableStack:use,adopt,defer,move, reverse-order disposal andSuppressedErrorJavaScript now has explicit resource management: using declarations and the DisposableStack class collect cleanup work… - Build an immutable
PlainDate: month arithmetic with end-of-month clamping, day differences without time zones, ISO weeks and comparisonBirthdays, due dates and billing days are calendar dates, not instants. Storing them in a Date ties them to a time zone:… - Parse an LLM streaming response: text deltas, tool-call arguments and content blocks by indexChat UIs built on LLM APIs receive the answer as a stream of Server-Sent Events. The text arrives in small deltas, a…
- Memoize a function by argument identity with a tree of Maps and WeakMapsJSON.stringify(args) is a poor cache key: two different objects with the same content collide, functions disappear, and…
- Implement
completeAssign()to copy getters, setters and symbol keysObject.assign reads each property and writes its value. A getter on the source runs once and the target gets a frozen… - Write an ES5
inherits()helper that links prototypes and static membersBefore class and extends, libraries shipped an inherits helper (Node still has util.inherits). Write a version that… - Model browser history with
visit,back(n)andforward(n)The back and forward buttons are a classic data-structure question. Implement class BrowserHistory that behaves like one… - Merge activity rows per user, summing numbers and de-duplicating listsAn analytics endpoint returns one row per session, and a dashboard needs one row per user. Implement mergeActivity(rows,…
- Write generators that flatten nested arrays lazily and walk a date rangeArray.prototype.flat builds the whole result at once, and a loop over dates written with local time skips or repeats a…
- Generate the shortest unique CSS class names in order, skipping reserved onesCSS minifiers and CSS-in-JS libraries rename long class names such as .product-card__title--active to the shortest names…
- Implement Observable
from,intervalandfromEventwith teardownQuestion 231 builds an Observable. This one is about the creation functions that turn everyday sources into observables,… - Keep an object and an input in sync both ways with property accessorsBefore frameworks, two-way data binding was built from property accessors: assigning user.name = "Ada" updates the text…
- Implement singleton, factory and strategy patterns idiomatically in JavaScriptA checkout module needs three small building blocks. Write each one with closures and plain objects or Maps; no class…
- Build a mini shell over an in-memory file system:
mkdir,cd,lsandpwdBuild the core of a terminal for a browser-based coding sandbox: a small shell over an in-memory file system. It starts… - Build a task queue with K workers, task ids, success and error callbacks and a pluggable executorBuild the job runner behind a dashboard that fires many API calls: at most K run at the same time, each task has an id…
- Build a
Thesaurusclass: add synonyms, look up related words and merge groups without duplicatesBuild the data structure behind a "related words" panel in a writing app. Synonymy is treated as an equivalence: if… - Build a
HistoryManagerclass with undo, redo, a size limit and grouped changesEditors, form builders and drawing tools all need undo and redo. Build a small framework-free HistoryManager that keeps… - Build a fantasy team selection validator: credits, squad size, role limits and a per-team capOn a fantasy sports app, a user builds a team of 11 real players before a match. The team selection screen greys out…
- Work out when scripts run: classic,
async,defer, module and inline scripts against the parserFree"Where should the <script> tag go, and what do async and defer change?" is a standard question. Answer it precisely by… - Build a resource pool:
acquire()andrelease()with a maximum size, a wait queue and timeoutsOpening a resource can be expensive: a WebSocket, a Web Worker, a database connection in a Node backend-for-frontend, a… - Build a tree of locks:
lock,unlockandupgradeon an m-ary tree with ancestor and descendant rulesA tree of named nodes (countries under continents under World, folders under a drive, rows under groups in a grid) needs… - Implement
test.: array rows, printf titles likeeach %sand%#, and tagged template tables with$nameParameterised tests are a favourite interview topic: "how would you test this function against twenty inputs without… - Rewrite imports like the Vite dev server: bare specifiers to pre-bundled deps,
?importon assetsBrowsers can load ES modules, but only by URL: import { ref } from "vue" fails, because "vue" is not a URL. In… - Build an
ObservableMapthat emitsset,deleteandclearevents to its listenersState libraries, caches and devtools all need to know when a collection changes. Implement class ObservableMap extends…
Hard22
- Implement
asyncMap()over an async iterable with bounded concurrency and backpressureImplement an async generator asyncMap(source, mapper, { concurrency = 4, ordered = true } = {}). source is any iterable… - Design Google Maps/Uber live tracking: map rendering, location updates, smoothing, and state synchronizationFreeDesign the live-tracking screen of a ride-hailing or delivery app (like Uber's "your driver is arriving" view):
- Design a travel-booking search page like Airbnb, with map, list and filters in syncDesign the search results page of a travel-booking site like Airbnb or Booking.com:
- Simulate ES module evaluation order: cycles, TDZ errors and slow top-level
await"Why does this import crash with Cannot access 'X' before initialization, but only when the app starts from a different… - Build a mini module bundler: resolve imports, build the graph, handle cycles and emit one runnable bundle"How does webpack or Rollup turn a folder of ES modules into one file?" is a staff-level favourite, because the answer…
- Design a food delivery app like Swiggy or Zomato: restaurant listing, menu customisations, cart rules and live order trackingDesign the web frontend (desktop and mobile web) of a food delivery app like Swiggy, Zomato or DoorDash. Users:
- Design a live election results page for huge traffic spikes: static shells, edge caching, incremental updates and mapsDesign the frontend of a live election results site for a national news organisation. On counting day, traffic goes from…
- Design a store locator with 50,000 map markers: clustering, viewport queries, list-map sync and accessibilityDesign the store locator for a large retail or services chain: think a bank's branch and ATM finder, a fuel company, or…
- Build an earliest-deadline-first job scheduler with preemption at yield pointsThe main thread cannot be interrupted, so long work in a page is split into slices that give control back regularly.…
- Implement
combineLatest,zipandwithLatestFromover async iterablesRxJS has three classic operators for combining streams. They are just as useful over async iterables (async generators,… - Design a live world map that shows a blip for every new member when data arrives only every 5 minutesDesign a "live" world map for a large social network's public page or office screens. Whenever someone joins, a small…
- Design a bike-sharing web app: station map, live availability, booking, rides and paymentsDesign the mobile-first web app of a city bike-sharing service. Riders:
- Resolve module specifiers with an import map:
imports, trailing-slash prefixes and the most specificscopes<script type="importmap"> lets a page write import React from "react" with no bundler: the browser looks the bare… - Simulate tree shaking: follow imports and re-exports, keep side-effectful modules and report what is removed"Why is my bundle still huge after tree shaking?" usually comes down to two things: barrel files that re-export…
- Design a ride-booking flow like Uber or Ola: pickup and drop selection, fare estimates, driver matching states and cancellationDesign the web frontend (mobile web and desktop) of a ride-hailing app like Uber or Ola, from choosing where to go to…
- Design an address autocomplete with a map pin: session tokens, cost control, keyboard support and Indian addressesDesign the "Add delivery address" screen of an Indian e-commerce or food delivery app on mobile web and desktop. The…
- Track selection in an infinite list with select all and exclusionsMail clients, file managers and admin tables let you tick rows in a list that loads more as you scroll, click "select…
- Build a parking lot manager: object model and UIParking lots are the classic object-oriented machine-coding round. You get a few levels with small, medium and large…
- Build a redux-saga-style effect runner:
take,put,call,select,fork,cancelandtakeLatestredux-saga runs side effects as generator functions that yield descriptions of what they want (take an action, call a… - Implement webpack's module runtime:
__webpack_require__, its cache, ESM interop and circular requiresEvery webpack bundle starts with a small runtime. Modules become functions in a table, and __webpack_require__(id) runs… - Build a mini webpack-style bundler for mixed ES modules and CommonJS with default-import interopReal projects mix formats: your code is ES modules, while many npm packages still ship CommonJS (require,…
- Design Google Maps on the web: map tiles, pan and zoom, viewport loading, search and directionsDesign the web version of a map product like Google Maps (maps.google.com) or OpenStreetMap's website. Users can:
Practise with tests and full answers.
Every question has a runnable editor, tests and a step-by-step solution. Passes from ₹149, paid once; nothing renews.
Frequently asked
What are the most asked ES6 interview questions?
The difference between var, let and const, arrow functions and this, destructuring, spread versus rest, template literals, classes versus constructor functions, promises, Map versus an object, Set for removing duplicates, symbols, iterators and generators, and ES modules versus CommonJS.
Is ES6 the same as modern JavaScript?
ES6 is the 2015 edition, the biggest single update. A new edition has come out every year since, adding features such as async/await, optional chaining, nullish coalescing and array methods like at and toSorted. Interviews often say ES6 when they mean any of these.
Are ES6 classes just syntax over prototypes?
Mostly. Methods still live on the prototype and inheritance still uses the prototype chain. But classes add rules: they must be called with new, their bodies are in strict mode, they support private # fields, and a subclass must call super before using this.