ES6+ JavaScript Interview Questions: Modern Features Explained
12 ES6+ JavaScript interview questions with answers and code: arrow functions, destructuring, spread vs rest, template literals, Map vs Object, Set, Symbol, generators, modules, optional chaining, nullish coalescing and structuredClone.
ES2015 (ES6) and the yearly releases after it changed how JavaScript is written. Interviewers use these features to check whether you write modern, readable code and understand the edge cases. Here are 12 ES6+ interview questions with answers and examples.
Syntax features#
Q1. How are arrow functions different from regular functions?#
| Regular function | Arrow function | |
|---|---|---|
this | Set by how it's called | Inherited from the enclosing scope |
arguments object | Yes | No (use rest parameters) |
Can be used with new | Yes | No |
prototype property | Yes | No |
| Implicit return | No | Yes, for single expressions |
const square = (n) => n * n;
const makeUser = (name) => ({ name }); // wrap object literals in ()
function regular() { return arguments.length; }
const arrow = (...args) => args.length; // rest instead of argumentsDeep dive: this, call, apply and bind interview questions.
Q2. Explain destructuring with defaults, renaming and nesting.#
const user = {
id: 7,
profile: { name: "Asha", city: "Pune" },
roles: ["admin", "editor"],
};
const {
id,
profile: { name: fullName, country = "India" }, // rename + default
roles: [primaryRole, ...otherRoles], // array destructuring + rest
} = user;
fullName; // "Asha"
country; // "India" (default because it's undefined)
primaryRole; // "admin"
otherRoles; // ["editor"]
// Swap without a temp variable
let a = 1, b = 2;
[a, b] = [b, a];
// Destructure function parameters with defaults
function connect({ host = "localhost", port = 5432 } = {}) {
return `${host}:${port}`;
}
connect(); // "localhost:5432"Note: defaults apply only when the value is undefined, not null.
Q3. What is the difference between the spread and rest operators?#
Answer: Both use .... Spread expands an iterable or object into individual items; rest collects remaining items into one array or object.
// Spread: expand
const merged = [...[1, 2], ...[3, 4]]; // [1, 2, 3, 4]
const settings = { ...defaults, ...userPrefs }; // later keys win
Math.max(...[5, 9, 2]); // 9
// Rest: collect
function sum(...nums) { return nums.reduce((a, b) => a + b, 0); }
const { password, ...safeUser } = user; // omit a key{ ...obj } and [...arr] copy only the top level. Nested objects are still shared with the original.
Q4. What are template literals and tagged templates?#
const name = "Ravi", items = 3;
const msg = `Hi ${name},
you have ${items} item${items === 1 ? "" : "s"} in your cart.`; // multi-line + expressions
// Tagged template: a function receives the string parts and values
function highlight(strings, ...values) {
return strings.reduce((out, str, i) =>
out + str + (i < values.length ? `<b>${values[i]}</b>` : ""), "");
}
highlight`Hello ${name}, total ${items}`;
// "Hello <b>Ravi</b>, total <b>3</b>"Tagged templates power libraries like styled-components, GraphQL's gql and safe SQL builders.
Data structures#
Q5. When should you use a Map instead of a plain object?#
| Object | Map | |
|---|---|---|
| Key types | Strings and Symbols | Any value, including objects |
| Order | Mostly insertion order, integers first | Strict insertion order |
| Size | Object.keys(o).length | map.size |
| Iteration | Needs Object.entries | Directly iterable |
| Prototype keys | Can clash (e.g. "constructor") | None |
| Frequent add/delete | Slower | Optimised |
const visits = new Map();
const userObj = { id: 1 };
visits.set(userObj, 3); // object as a key
visits.get(userObj); // 3
for (const [key, value] of visits) console.log(key, value);Use objects for fixed-shape records and JSON; use Map for dynamic dictionaries. WeakMap holds object keys weakly so they can still be garbage collected.
Q6. How do you remove duplicates from an array?#
const unique = [...new Set([3, 1, 3, 2, 1])]; // [3, 1, 2]
// Unique objects by a key
const users = [{ id: 1 }, { id: 2 }, { id: 1 }];
const byId = [...new Map(users.map((u) => [u.id, u])).values()];
// Set operations (ES2025)
const a = new Set([1, 2, 3]), b = new Set([2, 3, 4]);
a.intersection(b); // Set {2, 3}
a.union(b); // Set {1, 2, 3, 4}
a.difference(b); // Set {1}Q7. What is a Symbol, and why would you use one?#
Answer: A Symbol is a unique, immutable primitive often used as an object key that can't collide with any other key. Symbol keys are skipped by for...in, Object.keys and JSON.stringify. Built-in "well-known" symbols let you customise language behaviour.
const id = Symbol("id");
const user = { name: "Asha", [id]: 42 };
Object.keys(user); // ["name"]
user[id]; // 42
// Make any object iterable with Symbol.iterator
const range = {
from: 1, to: 3,
*[Symbol.iterator]() { for (let i = this.from; i <= this.to; i++) yield i; },
};
[...range]; // [1, 2, 3]Q8. What are generators, and where are they useful?#
Answer: A generator function (function*) can pause at yield and resume later, producing values lazily. Calling it returns an iterator.
function* idGenerator(prefix) {
let n = 1;
while (true) yield `${prefix}-${n++}`; // infinite, but lazy
}
const ids = idGenerator("order");
ids.next().value; // "order-1"
ids.next().value; // "order-2"
// Lazily take the first n items
function* take(iter, n) { for (const x of iter) { if (n-- <= 0) return; yield x; } }
[...take(idGenerator("u"), 3)]; // ["u-1", "u-2", "u-3"]Uses: infinite or lazy sequences, custom iterators, paginated API readers (async function* with for await...of), and libraries like redux-saga.
Modules and newer operators#
Q9. Compare ES modules with CommonJS.#
| ES modules | CommonJS | |
|---|---|---|
| Syntax | import / export | require / module.exports |
| Loading | Static, analysed before running (enables tree shaking) | Dynamic, at runtime |
| Bindings | Live, read-only bindings | Copied values at require time |
Top-level await | Supported | No |
| Where | Browsers, modern Node, bundlers | Older Node code |
// math.js
export const PI = 3.14;
export default function area(r) { return PI * r * r; }
// app.js
import area, { PI } from "./math.js";
const { heavyChart } = await import("./chart.js"); // dynamic import → code splittingQ10. What do optional chaining (?.) and nullish coalescing (??) do?#
const order = { customer: null, items: [] };
order.customer?.address?.city; // undefined instead of a TypeError
order.items?.[0]?.price; // safe array access
order.notify?.("shipped"); // call only if the method exists
const qty = 0;
qty || 10; // 10 (|| treats 0, "", false as missing)
qty ?? 10; // 0 (?? only replaces null or undefined)
let settings = {};
settings.theme ??= "dark"; // logical assignment: set only if null/undefinedUse ?? for defaults where 0, "" or false are valid values, such as a quantity, a page number or a toggle.
Q11. How do you deep clone an object in modern JavaScript?#
const original = { date: new Date(), tags: new Set(["a"]), nested: { n: 1 } };
const shallow = { ...original }; // nested still shared
const viaJson = JSON.parse(JSON.stringify(original));
// loses Date (becomes a string), Set (becomes {}), undefined, functions
const deep = structuredClone(original); // keeps Date, Set, Map, cycles
deep.nested.n = 2;
original.nested.n; // 1structuredClone can't copy functions, DOM nodes or class prototypes (instances become plain objects).
Q12. Name some useful features added after ES6.#
| Version | Feature | Example |
|---|---|---|
| ES2017 | async/await, Object.entries | for (const [k, v] of Object.entries(o)) |
| ES2019 | Array.flat, Object.fromEntries | [[1, [2]]].flat(Infinity) |
| ES2020 | ?., ??, BigInt, Promise.allSettled | 2n ** 64n |
| ES2021 | replaceAll, ??=, numeric separators | 1_000_000 |
| ES2022 | .at(), #private fields, top-level await, Object.hasOwn | arr.at(-1) |
| ES2023 | Non-mutating toSorted, toReversed, with, findLast | arr.toSorted() |
| ES2024 | Object.groupBy, Promise.withResolvers | Object.groupBy(users, (u) => u.role) |
Quick revision#
| Question | Short answer |
|---|---|
| Spread vs rest | Spread expands; rest collects |
Arrow function this | Lexical, from the outer scope |
| Object key that can't collide | Symbol |
?? vs || | ?? only replaces null/undefined |
| Deep clone | structuredClone |
| Why ES modules help bundlers | Static imports enable tree shaking |
Practise these features in JavaScript array methods interview questions.
Key takeaways#
- Arrow functions have lexical
this, noargumentsand can't be constructors. - Destructuring, spread and rest make data handling concise; remember spread copies are shallow.
- Use
MapandSetfor dynamic keys and uniqueness, and Symbols for collision-free keys. - ES modules are static and enable tree shaking; dynamic
import()enables code splitting. ?.,??andstructuredClonereplace many old defensive patterns.