Module 2: ES6+ Features
ES6 (2015) and later versions are the vocabulary of every modern codebase. This module covers arrow functions, destructuring, spread/rest, template literals, modules, and the modern operators you'll see in every code review.
2.1 Arrow Functions
Shorter syntax â and one crucial semantic difference: arrow functions have no this of their own. They inherit it from the surrounding scope.
// Syntax variations
const add = (a, b) => a + b; // implicit return
const square = n => n * n; // single param: parens optional
const random = () => Math.random(); // no params: parens required
const getUser = () => ({ id: 1 }); // returning an object: wrap in parens!
const process = (items) => { // multi-statement body: braces + return
const valid = items.filter(Boolean);
return valid.length;
};
// The `this` difference in action:
const timer = {
seconds: 0,
start() {
// Arrow inherits `this` from start() â works â
setInterval(() => this.seconds++, 1000);
// A regular function would get its own `this` (undefined) â breaks â
// setInterval(function () { this.seconds++; }, 1000);
}
};
- Object methods:
{ greet: () => this.name }âthisis NOT the object, it's whatever surrounds the literal. - Constructors: arrows can't be called with
new. - Anywhere you need
argumentsâ arrows don't have it (use rest params instead).
2.2 Template Literals
const name = "Veera", items = 3, price = 120;
// Interpolation with ${expression}
const msg = `Hi ${name}, your ${items} items cost âš${(items * price).toFixed(2)}`;
// Real multiline strings â great for SQL, HTML, emails
const query = `
SELECT id, name
FROM users
WHERE active = true
`;
2.3 Destructuring
Extract values from objects and arrays in one declarative step. You'll use this in nearly every function you write.
const response = {
status: 200,
data: { user: { id: 7, name: "Asha" }, meta: { page: 1 } },
};
// Basic + nested + rename + default, all at once:
const {
status,
data: {
user: { name: userName }, // nested + renamed â userName
meta: { limit = 20 }, // default when missing â limit = 20
},
} = response;
// Arrays: position-based
const [first, second, ...others] = [10, 20, 30, 40];
// first=10, second=20, others=[30, 40]
const [, runnerUp] = ["gold", "silver"]; // skip with commas
let a = 1, b = 2;
[a, b] = [b, a]; // swap without a temp var
// The killer use case: function parameters
function createServer({ port = 3000, host = "0.0.0.0", logger = console } = {}) {
logger.log(`Listening on ${host}:${port}`);
}
createServer({ port: 8080 }); // named "options object" pattern
createServer(); // = {} makes even the whole argument optional
// Destructuring in loops
const users = [{ id: 1, name: "A" }, { id: 2, name: "B" }];
for (const { id, name } of users) {
console.log(id, name);
}
Destructuring null/undefined throws: const { x } = undefined â TypeError. Defaults only kick in for undefined properties, not a missing object. Guard with = {} in parameters or optional chaining before destructuring.
2.4 Spread and Rest Operators
Identical syntax (...), opposite directions: spread expands a collection into pieces; rest collects pieces into a collection. Which one you're looking at depends on position â right side of = / in a call is spread; left side / in parameters is rest.
// ââ SPREAD ââââââââââââââââââââââââââââââ
const base = [1, 2, 3];
const extended = [0, ...base, 4]; // [0, 1, 2, 3, 4]
const copy = [...base]; // shallow copy
Math.max(...base); // 3 â spread into arguments
const defaults = { theme: "dark", fontSize: 14 };
const settings = { ...defaults, fontSize: 16 }; // later keys win â 16
// Idiomatic immutable update (Redux/React pattern, also great in Node):
const updatedUser = { ...user, lastLogin: Date.now() };
// ââ REST ââââââââââââââââââââââââââââââââ
function sum(...nums) { // variadic function
return nums.reduce((t, n) => t + n, 0);
}
sum(1, 2, 3, 4); // 10
const { password, ...safeUser } = user; // strip a field (API responses!)
const [head, ...tail] = [1, 2, 3]; // head=1, tail=[2,3]
const copy = { ...user } copies top-level keys only. Nested objects are still shared references: copy.address.city = "X" also changes user.address.city. For deep copies use structuredClone(user) (built into modern Node and browsers).
2.5 Modules (import / export)
ES Modules (ESM) are the standard way to split code across files. Every export is explicit; everything else stays private to the file.
// âââââ math.js âââââ
export const PI = 3.14159; // named export
export function area(r) { return PI * r * r; }
export default class Circle { // default export (max one per file)
constructor(r) { this.r = r; }
get area() { return area(this.r); }
}
// âââââ app.js âââââ
import Circle, { PI, area } from "./math.js"; // default + named together
import { area as circleArea } from "./math.js"; // rename on import
import * as math from "./math.js"; // namespace: math.PI, math.area()
// Dynamic import â returns a Promise (lazy loading!)
const { heavy } = await import("./heavy-module.js");
| Environment | How to enable ESM |
|---|---|
| Browser | <script type="module" src="app.js"> |
| Node.js | "type": "module" in package.json, or use .mjs extension |
| Older Node (CommonJS) | require() / module.exports â you'll still see this in legacy backend code; know both |
CommonJS (require) loads synchronously at runtime; ESM (import) is static, analyzed before execution â which enables tree-shaking and top-level await. New projects should use ESM. Interviewers love asking the difference.
2.6 Modern Operators & Friends (ES2020+)
// Optional chaining â safe navigation, no more "cannot read property of undefined"
const city = user?.address?.city; // undefined instead of crash
const len = order?.items?.length ?? 0;
user?.notify?.(); // call a method only if it exists
// Nullish coalescing â default ONLY for null/undefined
const port = config.port ?? 3000; // keeps 0 or "" if explicitly set
const bad = config.port || 3000; // â ī¸ || would wrongly replace 0 with 3000
// Logical assignment
options.retries ??= 3; // assign only if null/undefined
// Shorthand properties & computed keys
const name = "Asha", role = "dev";
const user2 = { name, role, [`key_${role}`]: true };
// Enhanced literals: method shorthand
const api = {
get(path) { return fetch(path); }, // instead of get: function(path)
};
Common Beginner Mistakes
- Arrow functions as object methods â
thiswon't be the object. - Forgetting parens when arrow-returning an object:
() => { id: 1 }is a block with a label, returnsundefined. Write() => ({ id: 1 }). - Treating spread as a deep copy and getting spooky shared-state bugs.
- Using
||for defaults when0,"", orfalseare valid values â use??. - Mixing default and named import syntax:
import { default }isn't a thing; it'simport Thing, { other }. - Circular imports between modules â usually a sign two files should be restructured or a shared piece extracted.
Exercises
// Rewrite using arrows, destructuring, template literals, and defaults:
function describe(user) {
var name = user.name;
var role = user.role || "guest";
return "User " + name + " has role " + role;
}
Solution
const describe = ({ name, role = "guest" }) => `User ${name} has role ${role}`;
Note: role = "guest" in destructuring only defaults on undefined, while the original || also replaced "" and null. Usually the destructuring default is what you actually want.
const person = {
name: "Ravi",
greet: () => `Hello, ${this?.name}`,
greet2() { return `Hello, ${this.name}`; },
};
console.log(person.greet());
console.log(person.greet2());
Solution
greet() â "Hello, undefined" â arrow inherits this from module scope, not person. greet2() â "Hello, Ravi" â method shorthand gets this from the call site (person.).
Write three pure functions using only spread/rest/destructuring (no mutation): addTag(post, tag), removeField(obj, key), and mergeSettings(defaults, overrides).
Solution
const addTag = (post, tag) => ({ ...post, tags: [...post.tags, tag] });
const removeField = (obj, key) => {
const { [key]: _removed, ...rest } = obj; // computed key + rest
return rest;
};
const mergeSettings = (defaults, overrides) => ({ ...defaults, ...overrides });
Given a possibly-incomplete config object, extract host (default "localhost"), port (default 3000, but 0 must be respected), and db.name (default "app") â without any crashes even if config or config.db is undefined. One expression each.
Solution
const host = config?.host ?? "localhost";
const port = config?.port ?? 3000; // ?? keeps port 0; || would not
const dbName = config?.db?.name ?? "app";
// Or with destructuring in one go:
const { host: h = "localhost", port: p = 3000, db: { name = "app" } = {} } = config ?? {};
Take your Module 1 expense tracker and split it into three ESM files: expenses.js (pure logic, named exports), format.js (a default-exported currency formatter), and main.js (imports both, runs a demo). Run it with node main.js after setting "type": "module" in package.json. Bonus: lazy-load format.js with a dynamic import().
Build a small quiz engine (Node or browser) where questions live in one module, scoring logic in another, and the runner imports both. Use destructuring for question fields, spread for immutable score updates, and template literals for output. Full spec on the Projects page.
Interview Questions from This Module
How do arrow functions differ from regular functions?
Four differences: (1) no own this â inherited lexically; (2) no arguments object; (3) can't be used as constructors with new; (4) no own prototype. Plus the obvious: shorter syntax with implicit return.
What's the difference between ?? and ||?
|| returns the right side for any falsy left value (0, "", false, NaN, null, undefined). ?? only falls through for null and undefined â so legitimate falsy values like 0 survive. Use ?? for defaults.
Is spread a deep or shallow copy? How do you deep-copy?
Shallow â nested objects remain shared references. For deep copies use structuredClone() (modern standard), or JSON.parse(JSON.stringify(x)) as the legacy hack (loses Dates, functions, undefined).
ESM vs CommonJS â key differences?
ESM: import/export, static analysis (tree-shaking), asynchronous loading, top-level await, strict mode by default. CommonJS: require/module.exports, synchronous, dynamic (can require conditionally anywhere). Node supports both; new code should prefer ESM.