JavaScript ES6 to ES2026: Modern Features Year by Year

JavaScript gets a new edition every June, named after the year: ES2015 (better known as ES6), ES2016, and so on up to ES2026. Each one adds features that make code shorter and safer. When you read a modern codebase or a Playwright project you meet all of them, and interviewers like to ask “what is new in recent JavaScript?”. This lesson is a guided tour: a quick recap of the big ES6 features you already learned, then each later edition with runnable examples of the features that matter most in day-to-day and test code. Every example ran on Node.js 26.

Advertisement

📖 What You’ll Learn: how ECMAScript editions and TC39 work, the ES6 (ES2015) essentials, includes and ** (ES2016), async/await and Object.entries (ES2017), object spread and finally (ES2018), flat and fromEntries (ES2019), optional chaining, nullish coalescing, BigInt and allSettled (ES2020), replaceAll, Promise.any and logical assignment (ES2021), class fields, at() and error cause (ES2022), non-mutating array methods (ES2023), groupBy and withResolvers (ES2024), iterator helpers, Set methods, Promise.try and RegExp.escape (ES2025), and the newest features shipping in 2026.


📅 How JavaScript Versions Work

Definition: ECMAScript (ES) is the official specification of the JavaScript language, maintained by the committee TC39. A new edition is published every year. Proposals move through stages 0–4; a proposal at stage 4 is finished and goes into the next edition.

  • ES6 = ES2015 was the huge update; since then each edition is small and yearly.
  • Browsers and Node.js often ship features before the edition is published, as soon as a proposal is stable.
  • Check support on MDN (the “Browser compatibility” table) or with typeof Feature before relying on very new features in browsers.

📄 versions.js

console.log("Node.js", process.version);
console.log("V8 engine", process.versions.v8);
console.log("Set.prototype.union exists:", typeof Set.prototype.union === "function");
console.log("Temporal exists:", typeof Temporal !== "undefined");

⌨️ Terminal

node versions.js

🖥️ Output

Node.js v26.13.0
V8 engine 14.6.202.34-node.40
Set.prototype.union exists: true
Temporal exists: true

🧱 ES2015 (ES6): The Foundation

You have used all of these throughout this course. Here they are together, as a quick reference:

📄 es6.js

const user = { name: "Asha", role: "tester", skills: ["Playwright", "SQL"] };

const { name, role = "guest", ...rest } = user;          // destructuring, default, rest
const [first] = user.skills;
const greet = (who = "QA") => `Hello, ${who}!`;          // arrow function, default parameter, template literal
const copy = { ...user, role: "lead" };                  // spread (objects are ES2018, arrays ES6)

class Test {                                              // class
  constructor(title) { this.title = title; }
  toString() { return `Test: ${this.title}`; }
}

const seen = new Set(["login", "login", "cart"]);        // Set and Map
const status = new Map([["login", "passed"]]);

function* ids() { let i = 1; while (true) yield i++; }  // generator
const gen = ids();

console.log(name, role, rest, first);
console.log(greet(), greet(name), copy.role);
console.log(String(new Test("checkout")));
console.log([...seen], status.get("login"), gen.next().value, gen.next().value);
for (const skill of user.skills) console.log("skill:", skill);   // for...of

⌨️ Terminal

node es6.js

🖥️ Output

Asha tester { skills: [ 'Playwright', 'SQL' ] } Playwright
Hello, QA! Hello, Asha! lead
Test: checkout
[ 'login', 'cart' ] passed 1 2
skill: Playwright
skill: SQL

ES6 also brought let/const, promises, modules (import/export), Symbol and the iteration protocol. Each has its own lesson earlier in this course.


🔧 ES2016 to ES2019: Small but Everyday

📄 es2016-2019.js

// ES2016
console.log([1, 2, NaN].includes(NaN), 2 ** 10);                  // includes, exponent operator

// ES2017
const scores = { login: 92, cart: 78 };
console.log(Object.entries(scores), Object.values(scores));
console.log("7".padStart(3, "0"), "ID".padEnd(5, ".") + "|");

// ES2018
const { login, ...others } = scores;                                // object rest
console.log(others, { ...scores, search: 85 });                     // object spread
const m = "2026-11-23".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
console.log(m.groups.year, m.groups.month);                         // named capture groups

// ES2019
console.log([[1, 2], [3, [4]]].flat(), [[1, 2], [3, [4]]].flat(Infinity));
console.log(["a b", "c"].flatMap((s) => s.split(" ")));
console.log(Object.fromEntries([["env", "staging"], ["retries", 2]]));
console.log("  padded  ".trimStart() + "|");
try { JSON.parse("{"); } catch { console.log("optional catch binding: no (e) needed"); }

⌨️ Terminal

node es2016-2019.js

🖥️ Output

true 1024
[ [ 'login', 92 ], [ 'cart', 78 ] ] [ 92, 78 ]
007 ID...|
{ cart: 78 } { login: 92, cart: 78, search: 85 }
2026 11
[ 1, 2, 3, [ 4 ] ] [ 1, 2, 3, 4 ]
[ 'a', 'b', 'c' ]
{ env: 'staging', retries: 2 }
padded  |
optional catch binding: no (e) needed

ES2017’s biggest feature, async/await, and ES2018’s Promise.prototype.finally and for await...of are covered in Module 10.


❓ ES2020: Optional Chaining, Nullish Coalescing and More

ES2020 removed a whole class of “Cannot read properties of undefined” errors:

📄 es2020.mjs

const response = { data: { user: { name: "Asha", address: null } } };

// optional chaining ?. stops and returns undefined instead of throwing
console.log(response.data?.user?.address?.city);
console.log(response.data?.orders?.[0]);
console.log(response.data.user.getAge?.());          // call only if the method exists

// nullish coalescing ?? uses the fallback only for null/undefined (not 0 or "")
const settings = { retries: 0, title: "" };
console.log(settings.retries || 3, settings.retries ?? 3);
console.log(JSON.stringify(settings.title || "Untitled"), JSON.stringify(settings.title ?? "Untitled"));

// BigInt for integers beyond Number.MAX_SAFE_INTEGER
console.log(9007199254740993n + 2n, typeof 10n);

// Promise.allSettled waits for all, never rejects
const results = await Promise.allSettled([Promise.resolve("ok"), Promise.reject(new Error("500"))]);
console.log(results.map((r) => r.status));

// globalThis, String.matchAll
console.log(typeof globalThis.setTimeout);
console.log([..."id=1&id=2".matchAll(/id=(\d)/g)].map((m) => m[1]));

⌨️ Terminal

node es2020.mjs

🖥️ Output

undefined
undefined
undefined
3 0
"Untitled" ""
9007199254740995n bigint
[ 'fulfilled', 'rejected' ]
function
[ '1', '2' ]

💡 Tip: The difference between || and ?? is a favourite interview question: 0 || 3 is 3, but 0 ?? 3 is 0. Use ?? for config values where 0, false or “” are valid.


Advertisement

✨ ES2021 and ES2022

📄 es2021-2022.mjs

// ES2021
console.log("a-b-c".replaceAll("-", "/"));
console.log(await Promise.any([Promise.reject(new Error("mirror 1 down")), Promise.resolve("mirror 2")]));
const budget = 1_000_000;                                      // numeric separators
console.log(budget);

const config = { retries: 0, baseURL: undefined };
config.retries ||= 2;                                           // assign if falsy
config.baseURL ??= "http://localhost:3000";                     // assign if null/undefined
config.timeout &&= 5000;                                        // assign if truthy (here: stays undefined)
console.log(config);

// ES2022
class Counter {
  #count = 0;                                                   // private field
  static created = 0;                                           // static field
  static { Counter.created = 0; }                               // static initialization block
  increment() { return ++this.#count; }
}
const c = new Counter();
c.increment();
console.log(c.increment(), Object.keys(c));

const arr = ["login", "cart", "logout"];
console.log(arr.at(-1), "first".at(0));                         // negative index
console.log(Object.hasOwn({ a: 1 }, "a"));

try {
  try { JSON.parse("{bad"); }
  catch (err) { throw new Error("Could not load test data", { cause: err }); }   // error cause
} catch (e) {
  console.log(e.message, "<-", e.cause.name);
}

⌨️ Terminal

node es2021-2022.mjs

🖥️ Output

a/b/c
mirror 2
1000000
{ retries: 2, baseURL: 'http://localhost:3000' }
2 []
logout f
true
Could not load test data <- SyntaxError

ES2022 also standardised top-level await in modules, which the two examples above rely on (they are .mjs files).


🧊 ES2023 and ES2024: Safer Arrays, groupBy and More

sort(), reverse() and splice() change the original array, a common source of bugs when test data is shared. ES2023 added copies that leave the original alone:

📄 es2023.js

const scores = [70, 95, 82];

const sorted = scores.toSorted((a, b) => b - a);       // new array
const reversed = scores.toReversed();
const withFix = scores.with(1, 96);                    // copy with one element replaced
const without = scores.toSpliced(0, 1);
console.log(scores, sorted, reversed, withFix, without);

console.log(scores.findLast((s) => s > 75), scores.findLastIndex((s) => s > 75));

⌨️ Terminal

node es2023.js

🖥️ Output

[ 70, 95, 82 ] [ 95, 82, 70 ] [ 82, 95, 70 ] [ 70, 96, 82 ] [ 95, 82 ]
82 2

ES2024 added grouping, a cleaner way to create promises you resolve later, and well-formed string checks:

📄 es2024.mjs

const results = [
  { test: "login", status: "passed" },
  { test: "cart", status: "failed" },
  { test: "search", status: "passed" },
  { test: "pay", status: "skipped" },
];

const byStatus = Object.groupBy(results, (r) => r.status);
console.log(Object.keys(byStatus), byStatus.passed.map((r) => r.test));

const byFirstLetter = Map.groupBy(results, (r) => r.test[0]);
console.log(byFirstLetter.get("p").length);

const { promise, resolve } = Promise.withResolvers();
setTimeout(() => resolve("server ready"), 10);
console.log(await promise);

console.log("abc".isWellFormed(), "\uD800".isWellFormed());

⌨️ Terminal

node es2024.mjs

🖥️ Output

[ 'passed', 'failed', 'skipped' ] [ 'login', 'search' ]
1
server ready
true false

🚀 ES2025: Iterator Helpers, Set Methods, Promise.try

Iterator helpers bring map, filter, take and friends to any iterator. They are lazy: they only compute the values you actually use, so they even work on infinite sequences:

📄 iterators.js

function* testIds() {
  let n = 1;
  while (true) yield `TC-${String(n++).padStart(3, "0")}`;   // infinite!
}

const firstEvenIds = testIds()
  .filter((id) => Number(id.slice(3)) % 2 === 0)
  .map((id) => id.toLowerCase())
  .take(3)
  .toArray();
console.log(firstEvenIds);

const map = new Map([["login", 2], ["cart", 5]]);
console.log(map.keys().map((k) => k.toUpperCase()).toArray());

⌨️ Terminal

node iterators.js

🖥️ Output

[ 'tc-002', 'tc-004', 'tc-006' ]
[ 'LOGIN', 'CART' ]

Set methods finally give sets their mathematical operations, handy for comparing expected and actual lists:

📄 sets.js

const expected = new Set(["Home", "Courses", "Practice", "Blog"]);
const actual = new Set(["Home", "Courses", "Blog", "Jobs"]);

console.log("missing:", [...expected.difference(actual)]);
console.log("unexpected:", [...actual.difference(expected)]);
console.log("common:", [...expected.intersection(actual)]);
console.log("all:", [...expected.union(actual)]);
console.log("same menu?", expected.isSubsetOf(actual) && actual.isSubsetOf(expected));

⌨️ Terminal

node sets.js

🖥️ Output

missing: [ 'Practice' ]
unexpected: [ 'Jobs' ]
common: [ 'Home', 'Courses', 'Blog' ]
all: [ 'Home', 'Courses', 'Practice', 'Blog', 'Jobs' ]
same menu? false

Also in ES2025: Promise.try, RegExp.escape, JSON modules with import attributes, and Float16Array:

📄 package.json

{ "name": "qa-framework", "version": "1.0.0" }

📄 es2025.mjs

import pkg from "./package.json" with { type: "json" };    // JSON module
console.log(pkg.name);

// Promise.try: run a function that may throw OR return a promise, always get a promise
const parse = (text) => JSON.parse(text);
await Promise.try(parse, "{bad").catch((e) => console.log("caught:", e.name));

// RegExp.escape: search for user text safely
const userInput = "price (USD) $10?";
const re = new RegExp(RegExp.escape(userInput));
console.log(re.test("Filter: price (USD) $10?"), new RegExp(userInput).test("Filter: price (USD) $10?"));

⌨️ Terminal

node es2025.mjs

🖥️ Output

qa-framework
caught: SyntaxError
true false

Advertisement

🆕 The Newest Features (2026)

These features are recently standardised or finishing standardisation, and already ship in Node.js 26 and current browsers. Several belong to ES2026; for the rest, check MDN’s compatibility table before using them in code that must run in older browsers:

📄 newest.mjs

// Error.isError: reliable check, even for errors from other realms (iframes, vm)
console.log(Error.isError(new TypeError("x")), Error.isError({ message: "fake" }));

// Array.fromAsync: collect an async iterable into an array
async function* pages() { yield "page 1"; yield "page 2"; }
console.log(await Array.fromAsync(pages()));

// Base64 and hex directly on Uint8Array
const bytes = new TextEncoder().encode("QA");
console.log(bytes.toBase64(), bytes.toHex(), new TextDecoder().decode(Uint8Array.fromBase64("UUE=")));

// Map.getOrInsert / getOrInsertComputed (often called "upsert")
const failures = new Map();
for (const test of ["login", "cart", "login"]) {
  failures.set(test, failures.getOrInsert(test, 0) + 1);
}
console.log(failures);

// Iterator.concat
console.log(Iterator.concat(["smoke"], new Set(["regression"])).toArray());

⌨️ Terminal

node newest.mjs

🖥️ Output

true false
[ 'page 1', 'page 2' ]
UUE= 5141 QA
Map(2) { 'login' => 2, 'cart' => 1 }
[ 'smoke', 'regression' ]

using: automatic clean-up

A using declaration calls an object’s [Symbol.dispose]() method automatically when the block ends, even if an error is thrown, like try...finally without the boilerplate. It is ideal for test resources such as temporary files, servers or browser pages:

📄 using.mjs

function openTempServer(name) {
  console.log(`start ${name}`);
  return { name, [Symbol.dispose]() { console.log(`stop ${name}`); } };
}

{
  using api = openTempServer("mock API");
  using db = openTempServer("test DB");
  console.log(`running tests against ${api.name} and ${db.name}`);
}   // disposed here, in reverse order
console.log("after the block");

⌨️ Terminal

node using.mjs

🖥️ Output

start mock API
start test DB
running tests against mock API and test DB
stop test DB
stop mock API
after the block

Temporal: a modern date and time API

Temporal replaces the error-prone Date object with immutable, time-zone-aware types. It is covered in the dates lesson; here is a taste:

📄 temporal.js

const release = Temporal.PlainDate.from("2026-11-23");
console.log(release.add({ days: 10 }).toString(), release.dayOfWeek, release.daysInMonth);
console.log(Temporal.PlainDate.from("2024-01-31").add({ months: 1 }).toString());   // clamps to Feb 29

⌨️ Terminal

node temporal.js

🖥️ Output

2026-12-03 1 30
2024-02-29

🧪 Tester Scenario: Modernising Old Test Code

The same helper written in older style and in modern JavaScript. Both give identical results, but the modern version is shorter and avoids mutation and crashes on missing data:

📄 modernise.js

const runs = [
  { id: 1, suite: "smoke", result: { status: "passed", ms: 1200 } },
  { id: 2, suite: "smoke", result: { status: "failed", ms: 900 } },
  { id: 3, suite: "regression", result: null },
  { id: 4, suite: "regression", result: { status: "passed", ms: 0 } },
];

// old style (ES5)
function summaryOld(list) {
  var out = {};
  for (var i = 0; i < list.length; i++) {
    var r = list[i];
    var status = r.result && r.result.status ? r.result.status : "not run";
    if (!out[r.suite]) out[r.suite] = [];
    out[r.suite].push(r.id + ":" + status + ":" + (r.result && r.result.ms !== undefined ? r.result.ms : "-"));
  }
  return out;
}

// modern style
const summaryNew = (list) =>
  Object.fromEntries(
    Object.entries(Object.groupBy(list, (r) => r.suite)).map(([suite, items]) => [
      suite,
      items.map(({ id, result }) => `${id}:${result?.status ?? "not run"}:${result?.ms ?? "-"}`),
    ])
  );

console.log(summaryOld(runs));
console.log(summaryNew(runs));
console.log("same result:", JSON.stringify(summaryOld(runs)) === JSON.stringify(summaryNew(runs)));

⌨️ Terminal

node modernise.js

🖥️ Output

{
  smoke: [ '1:passed:1200', '2:failed:900' ],
  regression: [ '3:not run:-', '4:passed:0' ]
}
{
  smoke: [ '1:passed:1200', '2:failed:900' ],
  regression: [ '3:not run:-', '4:passed:0' ]
}
same result: true

Note how result?.ms ?? "-" keeps the valid duration 0 for test 4, which an || would have turned into “-“.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Use optional chaining and nullish coalescing to print a user’s city, or “Unknown” if any part is missing.

Show answer

📄 practice1.js

const users = [{ address: { city: "Pune" } }, { address: null }, {}];
for (const u of users) console.log(u.address?.city ?? "Unknown");

🖥️ Output

Pune
Unknown
Unknown

Q2. Sort a copy of [3, 1, 2] in descending order without changing the original.

Show answer

📄 practice2.js

const nums = [3, 1, 2];
const desc = nums.toSorted((a, b) => b - a);
console.log(nums, desc);

🖥️ Output

[ 3, 1, 2 ] [ 3, 2, 1 ]

Q3. Group these bugs by severity with Object.groupBy and print how many are in each group.

[{ id: 1, sev: "high" }, { id: 2, sev: "low" }, { id: 3, sev: "high" }]
Show answer

📄 practice3.js

const bugs = [{ id: 1, sev: "high" }, { id: 2, sev: "low" }, { id: 3, sev: "high" }];
const groups = Object.groupBy(bugs, (b) => b.sev);
for (const [sev, list] of Object.entries(groups)) console.log(sev, list.length);

🖥️ Output

high 2
low 1

Q4. Find which expected browsers are missing from the tested list, using Set methods.

Show answer

📄 practice4.js

const expected = new Set(["chromium", "firefox", "webkit"]);
const tested = new Set(["chromium", "webkit"]);
console.log([...expected.difference(tested)]);

🖥️ Output

[ 'firefox' ]

Q5. Get the last element of an array with at() and the first 2 even numbers from an infinite generator with iterator helpers.

Show answer

📄 practice5.js

console.log(["a", "b", "c"].at(-1));
function* naturals() { let n = 1; while (true) yield n++; }
console.log(naturals().filter((n) => n % 2 === 0).take(2).toArray());

🖥️ Output

c
[ 2, 4 ]

Q6. What do these print, and why? 0 || 5, 0 ?? 5, null ?? 5, "" || "x", "" ?? "x"

Show answer

📄 practice6.js

console.log(0 || 5, 0 ?? 5, null ?? 5, JSON.stringify("" || "x"), JSON.stringify("" ?? "x"));

🖥️ Output

5 0 5 "x" ""

|| falls back for any falsy value (0, “”, false, null, undefined, NaN); ?? only for null and undefined.


🧠 MCQ Quiz: ES6 to ES2026 Features

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which committee maintains the JavaScript specification?
  2. Which edition is also known as ES6?
  3. What does obj?.a?.b return if obj.a is undefined?
  4. What is 0 ?? 10?
  5. Which method sorts without changing the original array?
  6. Which ES2024 feature groups items into an object by a key function?
  7. What is special about iterator helpers such as .map().take()?
  8. What does a.difference(b) return for two Sets?
  9. Which ES2022 syntax declares a private class field?
  10. What does a using declaration do?

💼 Interview Questions and Answers

Q1. What are the most important features added to JavaScript since ES6?

async/await (ES2017) for readable asynchronous code; object spread/rest (ES2018); optional chaining and nullish coalescing (ES2020) to handle missing data safely; Promise.allSettled and Promise.any; class private fields and top-level await (ES2022); non-mutating array methods like toSorted (ES2023); Object.groupBy (ES2024); and iterator helpers and Set methods (ES2025). In test code, ?., ??, async/await and the non-mutating methods are used constantly.

Q2. Explain the difference between || and ??.

a || b returns b whenever a is falsy: 0, "", false, NaN, null or undefined. a ?? b returns b only when a is null or undefined. Use ?? for defaults where 0, false or an empty string are legitimate values, such as retries: 0.

Q3. How does a new feature get into JavaScript?

Anyone can propose it to TC39. It moves through stages: 0 (idea), 1 (proposal), 2 (draft spec), 2.7 (approved in principle, awaiting tests), 3 (recommended for implementation) and 4 (finished: two compatible implementations and tests). Stage 4 proposals are added to the next yearly edition, published each June. Engines often ship features at stage 3.

Q4. Why prefer toSorted over sort in test code?

sort() sorts in place and returns the same array, so sorting shared test data or a fixture silently changes it for other tests and for later assertions. toSorted() returns a sorted copy and leaves the input untouched, which avoids order-dependent, hard-to-debug failures.


Advertisement

❓ Frequently Asked Questions

🤔 Do I need Babel to use modern JavaScript?

Not for Node.js 20+ or current browsers, which support almost everything up to ES2025. Transpilers are only needed to support old browsers, and TypeScript or bundlers handle that for you.

🤔 How do I check whether a feature is supported?

Look at the MDN page for the feature (Browser compatibility table) or caniuse.com, or test for it in code, for example typeof Object.groupBy === "function".

🤔 What is the difference between JavaScript and ECMAScript?

ECMAScript is the language specification. JavaScript is the language as implemented by engines (V8, SpiderMonkey, JavaScriptCore), plus host APIs such as the DOM in browsers or fs in Node.js.

🤔 Are the newest features safe to use in Playwright tests?

Yes. Test code runs on your Node.js version, so anything your Node.js supports works. Code passed to page.evaluate() runs in the browser, so check browser support for that part.


🏁 Summary

  • ECMAScript gets a new edition every June; TC39 proposals reach stage 4 before joining it.
  • ES6 gave the foundation: let/const, arrows, classes, modules, promises, destructuring, spread, Map/Set.
  • Everyday later additions: async/await, ?. and ??, logical assignment, at(), private fields, error cause.
  • Safer data handling: toSorted/toReversed/with, Object.groupBy, Set methods, lazy iterator helpers.
  • The newest features include Error.isError, Array.fromAsync, base64 on Uint8Array, using declarations and Temporal.

Next, continue with Lesson 64: Functional Programming.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in