Lesson 11 of 12 · 9 min · JavaScript in the browser

Modern JavaScript: the ES6+ features you use every day

Covers: JavaScript (ECMAScript 2025) in current browsers and Node.js 22 or newer. Updated 13 Nov 2026. Part of the Frontend Developer roadmap.

What you will learn

  • The ES6 (ES2015) features every codebase uses
  • Newer syntax from ES2016 to ES2025 that is safe in current browsers
  • When to use arrows, destructuring, spread, optional chaining and ??
  • Iterators, generators and symbols in plain terms
  • How to check browser support and use transpilers

In simple words

JavaScript is updated every year. A big update in 2015, called ES6, added the features that make today's code short and readable: arrow functions, template strings, let and const, classes, modules and promises. Newer years added smaller helpers for everyday jobs, like safely reading a property that might not exist. Knowing these is the difference between code that looks ten years old and code that reads like what you see in React, Node.js and job interviews.

Words to know

  • ES6 or ES2015: the 2015 edition of the JavaScript standard that modernised the language.
  • ECMAScript: the official name of the JavaScript language standard.
  • Transpiler: a tool such as Babel or TypeScript that turns new syntax into older syntax.
  • Polyfill: code that adds a missing feature to older browsers.

Template literals

const name = "Asha", amount = 1250;
const text = `Hello ${name}, your total is ₹${(amount * 1.18).toFixed(2)}.`;   // expressions inside ${}
const html = `
  <li class="order">
    ${name}
  </li>`;                                       // multi-line strings

Backticks allow interpolation and line breaks. Tagged templates (sql`select ... ${id}`) power libraries such as styled-components and safe SQL builders.

Arrow functions

const double = (n) => n * 2;                    // implicit return of one expression
const add = (a, b) => a + b;
const makeUser = (name) => ({ name, active: true });     // wrap an object literal in ()
const log = () => { console.log("hi"); };       // braces need an explicit return
[1, 2, 3].map((n) => n * 2);

Arrows are shorter and keep the surrounding this (the this lesson). Use normal functions for object methods needing their own this, for constructors and for hoisted utilities.

Default, rest and spread

function connect(host = "localhost", { port = 5432, ssl = false } = {}) { /* ... */ }

function total(first, ...rest) {                // rest: collects the remaining arguments into an array
  return rest.reduce((sum, n) => sum + n, first);
}

const all = [...a, ...b];                       // spread arrays
const copy = { ...user, city: "Pune" };         // spread objects (later keys win)
Math.max(...numbers);

Destructuring

const { name, email, address: { city } = {}, ...others } = user;
const [first, , third = "none", ...tail] = list;
const [min, max] = [Math.min(...nums), Math.max(...nums)];

for (const [key, value] of Object.entries(obj)) { /* ... */ }
function show({ title, price = 0 }) { /* destructure in the parameter list */ }

Optional chaining and nullish coalescing

const city = user?.address?.city;               // undefined if user or address is null/undefined
const first = list?.[0];
const result = callback?.(value);               // call only if it is a function

const limit = options.limit ?? 10;              // default only for null or undefined (keeps 0 and "")
settings.theme ??= "light";                     // assign only if null or undefined
count ||= 0;  flag &&= check();                 // logical assignment operators

?. removes long a && a.b && a.b.c chains; ?? fixes the || default problem with 0 and "".

let, const, and block scope

Covered earlier: prefer const, use let when reassigning, and avoid var. Block-scoped bindings remove the classic loop-closure bug.

Classes and modules

Classes with fields, private #members, static members and extends, and import/export modules (the earlier lessons). Related: getters and setters, static initialisation blocks, and top-level await in modules.

Promises and async/await

async and await (ES2017), Promise.allSettled (ES2020), Promise.any (ES2021), Promise.withResolvers (ES2024) and for await...of (ES2018): see the async lessons.

Useful newer methods

// Strings
"a-b-c".replaceAll("-", "+");                   // ES2021
"  hi ".trim();  "5".padStart(3, "0");          // "005"
"hello".at(-1);                                 // "o"  (ES2022)

// Arrays
[3, 1, 2].toSorted();                           // ES2023 non-mutating (also toReversed, toSpliced, with)
[1, 2, 3].at(-1);   [1, [2, [3]]].flat(Infinity);
[1, 2, 3, 4].findLast((n) => n % 2 === 1);      // 3  (ES2023)
Array.from({ length: 5 }, (_, i) => i * 2);     // [0, 2, 4, 6, 8]
Object.groupBy(orders, (o) => o.status);        // ES2024

// Objects
Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v * 2]));
Object.hasOwn(obj, "x");                        // ES2022, prefer over hasOwnProperty
structuredClone(value);                         // deep copy, a web platform API

// Sets (recent browsers and Node 22+)
new Set([1, 2]).union(new Set([2, 3]));         // also intersection, difference, isSubsetOf

// Numbers
1_000_000;  0b1010;  2 ** 10;  123n;            // separators, binary, exponent, BigInt
Number.isInteger(5);  Number.isNaN(NaN);

Other additions worth knowing: Intl (NumberFormat, DateTimeFormat, RelativeTimeFormat, PluralRules, Segmenter) for formatting amounts, dates and text in Indian locales without libraries; Error with cause; WeakMap/WeakRef; globalThis; regular expression named groups ((?<year>\d{4})) and the v flag; iterator helpers (Iterator.prototype.map, .filter, .take) in recent engines; and Promise.try and RegExp.escape in the newest editions. Check support before relying on the newest ones.

Iterators and generators

An iterable is anything you can loop over with for...of (arrays, strings, Map, Set, NodeList). A generator is a function that can pause and produce values one at a time with yield, great for lazy sequences:

function* range(start, end, step = 1) {
  for (let n = start; n < end; n += step) yield n;
}

for (const n of range(0, 10, 3)) console.log(n);     // 0 3 6 9
const firstThree = [...range(0, Infinity)].slice(0, 3);   // careful: infinite! use iterator helpers or a loop with break

Generators underpin async iteration and some state libraries; you will rarely write them in application code.

Symbols

Symbol("id") creates a unique value used as a hidden property key or a well-known protocol (Symbol.iterator, Symbol.asyncIterator). Most developers meet them only through libraries.

Support and tooling

  • Browser support: check MDN's compatibility tables and Can I use (caniuse.com), and aim for features marked "Baseline" (supported in all major current browsers). The browserslist setting in package.json tells tools which browsers you target (for example >0.5%, last 2 versions, not dead).
  • Transpiling: Vite, esbuild, SWC and Babel compile modern syntax for older browsers if needed, and TypeScript does the same for its syntax. Most Indian users are on recent Chrome and Android WebView, so you can often ship modern syntax; test on real low-end phones.
  • Polyfills: core-js adds missing methods; include only what your browser list needs, because they add weight.
  • Linting: ESLint with a modern config and Prettier for formatting catch outdated patterns (var, ==) for you.
  • Node.js: current LTS versions support nearly everything above, so use the Node version your platform recommends.

Style tips

  • Prefer const, arrow functions for callbacks, template literals, destructuring, ?. and ??, and array methods over manual loops.
  • Do not over-compress code: clarity beats cleverness (a long chain of ?. and ?? with side effects is hard to read).
  • Do not use spread to copy huge arrays in hot loops.
  • Use named exports and small modules.

Common mistakes

  • Returning an object literal from an arrow function without parentheses (() => { a: 1 } is a block).
  • Using || for defaults where ?? is correct.
  • Believing spread and destructuring make deep copies.
  • Using arrows as methods needing this.
  • Relying on features without checking support for your audience.
  • Mixing too many new features in one expression.

Try it yourself

  1. Rewrite a function from older code (with var, string concatenation, function callbacks and || defaults) using modern syntax.
  2. Use optional chaining and ?? to safely read response.data?.user?.profile?.city ?? "Unknown".
  3. Use Object.groupBy (or reduce) and Object.fromEntries to transform a list of orders into totals by status.
  4. Format a number and a date in the Indian locale with Intl.
  5. Write a generator idGenerator() that yields 1, 2, 3 and use it with next().

Check yourself

What is the difference between ?? and ||?

?? uses the fallback only when the left side is null or undefined; || uses it for any falsy value including 0, "" and false.

What does user?.address?.city return if address is missing?

undefined, without throwing an error.

Why wrap an object literal in parentheses when returning it from an arrow function?

Without parentheses, the braces are parsed as the function body, not an object.

What does a transpiler do?

It converts newer syntax into older syntax that older browsers understand; polyfills separately add missing library features.

Interview questions

Name some ES6 features and why they matter.

let and const (block scope), arrow functions (concise, lexical this), template literals, destructuring, spread and rest, default parameters, classes, modules, promises, Map and Set, and iterators and generators; together they made code shorter, safer and modular.

What is the difference between spread and rest?

Both use ...: rest collects several values into an array in a parameter list or destructuring; spread expands an array or object into individual elements or properties.

How do you use new JavaScript features while supporting older browsers?

Check support (MDN, Can I use), define a browserslist target, and use a build tool such as Vite, Babel or TypeScript to transpile syntax and add polyfills only where needed.

Summary

  • ES6 gave let/const, arrows, template literals, destructuring, spread, classes, modules and promises.
  • Later years added ?., ??, async/await, Object.entries/groupBy, immutable array methods, structuredClone and more.
  • Prefer clear modern syntax, with Intl for formatting; check support and let build tools handle old browsers.
  • Use ESLint and Prettier to keep code consistent.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on JavaScript from fundamentals to async for Frontend Developer and scores every answer, with what to fix.