ES6+ Modern JavaScript

Published by Brayan K

ES6 (ECMAScript 2015) and later versions are modern updates to JavaScript that add features like let/const, arrow functions, template literals, destructuring, classes, and modules to write cleaner, more powerful code.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Modernise a function without silently changing its contract

Shorter syntax is useful when it makes the same decisions easier to see. Start a refactor by naming those decisions: which inputs count as missing, whether input objects may change, and what the result contains. This card formatter uses a title default only for undefined, and a stock default for null or undefined.

function legacyCard(product) {
  var title = product.title; // Preserve empty strings and explicit null.
  if (title === undefined) title = "Untitled";
  var stock = product.stock;
  if (stock === null || stock === undefined) stock = 0;
  return { title: title, stock: stock, label: title + " (" + stock + ")" };
}
function modernCard(product) {
  const { title = "Untitled" } = product; // Only undefined takes this default.
  const stock = product.stock ?? 0; // Null and undefined mean no stock value.
  return { title, stock, label: `${title} (${stock})` };
}
const cases = [
  {},
  { title: "", stock: 0 },
  { title: "Loops", stock: null },
  { title: null, stock: 2 }
];
for (const product of cases) {
  const oldResult = legacyCard(product);
  const newResult = modernCard(product); // Compare the exact result on each boundary input.
  console.log(JSON.stringify(newResult));
  console.log(JSON.stringify(oldResult) === JSON.stringify(newResult));
}

// ✅ Expected output:
// {"title":"Untitled","stock":0,"label":"Untitled (0)"}
// true
// {"title":"","stock":0,"label":" (0)"}
// true
// {"title":"Loops","stock":0,"label":"Loops (0)"}
// true
// {"title":null,"stock":2,"label":"null (2)"}
// true

The null title deliberately remains null in both functions. Matching output proves equivalence for these fixtures, not for every possible object or side effect. Validation and behaviour changes should be explicit changes of contract, not accidental consequences of rewriting punctuation.

Keep defaults separate from validation

Replacing || with ?? changes which inputs trigger a fallback. Preserve zero or an empty string when the product contract accepts them; reject them explicitly when it does not. Optional Chaining & Nullish Coalescing owns the full operator rules.

const rows = [
  { label: "", count: 0 },
  { label: null, count: undefined },
  { label: "Ready", count: 3 }
];
for (const row of rows) {
  const before = { label: row.label || "Untitled", count: row.count || 10 };
  const after = { label: row.label ?? "Untitled", count: row.count ?? 10 };
  console.log(JSON.stringify(before));
  console.log(JSON.stringify(after));
}

// ✅ Expected output:
// {"label":"Untitled","count":10}
// {"label":"","count":0}
// {"label":"Untitled","count":10}
// {"label":"Untitled","count":10}
// {"label":"Ready","count":3}
// {"label":"Ready","count":3}

Destructuring defaults apply to undefined, so replacing a nullish fallback with a default pattern can change behaviour again. Destructuring Assignment owns defaults and renaming; use the expected input cases to choose between them.

const input = { title: null };
const { title = "Untitled" } = input;
const normalized = input.title ?? "Untitled";
console.log(title, normalized);

// ✅ Expected output:
// null Untitled

A default does not check a supplied value’s type. Optional access also does not prove that a non-null value has the right shape. Keep a deliberate validation boundary for data that your function does not control.

function cardTitle(input) {
  const title = input.title ?? "Untitled";
  if (typeof title !== "string") throw new TypeError("title must be a string");
  return { title };
}
console.log(JSON.stringify(cardTitle({ title: "" })));
console.log(JSON.stringify(cardTitle({})));
cardTitle({ title: 12 });

// ✅ Expected output:
// {"title":""}
// {"title":"Untitled"}

// ✅ Expected error:
// TypeError: title must be a string

Object shorthand uses existing variables; brackets choose a key

Property shorthand writes a property name and its same-named variable once. It does not declare a missing variable or turn a variable’s value into a key. Computed property syntax uses brackets when the key itself comes from an expression. These are different choices when constructing a record.

const title = "Loops";
const copies = 0;
const expanded = { title: title, copies: copies };
const compact = { title, copies };
console.log(JSON.stringify(compact));
console.log(JSON.stringify(expanded) === JSON.stringify(compact));

// ✅ Expected output:
// {"title":"Loops","copies":0}
// true
const record = { missingLabel };
console.log(record);

// ✅ Expected error:
// ReferenceError: missingLabel is not defined
const key = "theme";
const value = "dark";
const literalKey = { key: value };
const chosenKey = { [key]: value };
console.log(JSON.stringify(literalKey));
console.log(JSON.stringify(chosenKey));

// ✅ Expected output:
// {"key":"dark"}
// {"theme":"dark"}

Method shorthand supplies a method function without the function keyword. Do not replace a receiver-dependent method with an arrow just because it is shorter. The this Keyword owns receiver rules and arrow capture.

"use strict";
function makeCounter(start) {
  return {
    count: start,
    increment() { this.count++; return this.count; }
  };
}
const counter = makeCounter(2);
console.log(counter.increment());
console.log(counter.count);
const detached = counter.increment;
detached();

// ✅ Expected output:
// 3
// 3

// ✅ Expected error:
// TypeError: Cannot read properties of undefined (reading 'count')

Keep expression returns visible when shortening callbacks

An arrow expression can return a value without return. A braced function body needs an explicit return; an object expression needs parentheses in the concise form. Functions owns function syntax, while map, filter & reduce owns callback result shapes.

const records = [{ title: "Loops" }];
const broken = records.map(record => { title: record.title });
const fixed = records.map(record => ({ title: record.title }));
console.log(broken[0] === undefined);
console.log(JSON.stringify(fixed));

// ✅ Expected output:
// true
// [{"title":"Loops"}]

A statement inside a braced callback is not automatically its result. During a refactor, compare both the number of results and their values; serializing undefined array entries can disguise the missing return as null.

Make override order and copy depth part of the review

Object spread order determines which property wins. Reordering a defaults merge can undo the caller’s settings. Spread only copies one level; Spread & Rest Operators owns the full copying rules.

const defaults = { theme: "light", pageSize: 20 };
const supplied = { pageSize: 0 };
console.log(JSON.stringify({ ...defaults, ...supplied }));
console.log(JSON.stringify({ ...supplied, ...defaults }));

// ✅ Expected output:
// {"theme":"light","pageSize":0}
// {"pageSize":20,"theme":"light"}
const original = { layout: { compact: false }, label: "Notes" };
const copy = { ...original };
copy.layout.compact = true;
console.log(original === copy);
console.log(original.layout === copy.layout);
console.log(original.layout.compact);

// ✅ Expected output:
// false
// true
// true

Use tests that inspect the original input as well as the returned value. A function can print the expected result and still violate an “input stays unchanged” contract.

ES6+ names a family of editions, not one compatibility target

ES6 is ECMAScript 2015; the plus sign includes later editions. Optional chaining and nullish coalescing were added after ES2015, so a promise to support only ES6 syntax does not automatically cover them. Choose the browsers or runtimes your project supports and check the features you actually use.

A syntax transform and a missing runtime API are different problems. Rewriting arrow syntax does not itself provide a missing built-in method. Modules also depend on the host’s module-loading setup: JavaScript Modules: ES6 Imports, Exports, Bundling owns import/export and resolution; Prototypes and Classes owns class construction. This page’s examples are complete scripts and use no module loader.

Guided exercise: preserve a zero stock count

Complete the title binding, nullish fallback and shorthand property using the literal hints. The supplied zero must remain zero, and the empty title must remain an empty string.

const input = { title: "", stock: 0 };
const { ___ = "Untitled" } = input; // 👉 replace ___ with title
const stock = input.stock ___ 10; // 👉 replace ___ with ??
const card = { title, ___ }; // 👉 replace ___ with stock
console.log(JSON.stringify(card));

// ✅ Expected output:
// {"title":"","stock":0}

Independent brief: build settings with an explicit boundary

Write buildSettings(input). Accept an object, null or undefined at the root; treat nullish roots as empty settings. Reject arrays and other root types. An optional layout must also be an object or nullish, not an array. Use defaults of theme="light", pageSize=20 and compact=false only for nullish field values.

Require theme to be a string (including an allowed empty string), pageSize to be an integer from 0 through 100, and compact to be Boolean. Return only theme, pageSize and a newly constructed layout containing compact. Do not modify or share the input layout. Check valid zero/false/empty-string values, nullish input, repeated calls and invalid field types.

function buildSettings(input) {
  const source = input ?? {};
  if (typeof source !== "object" || Array.isArray(source)) {
    throw new TypeError("settings must be an object");
  }
  const sourceLayout = source.layout ?? {};
  if (typeof sourceLayout !== "object" || Array.isArray(sourceLayout)) {
    throw new TypeError("layout must be an object");
  }
  const theme = source.theme ?? "light";
  const pageSize = source.pageSize ?? 20;
  const compact = sourceLayout.compact ?? false;
  if (typeof theme !== "string") throw new TypeError("theme must be a string");
  if (!Number.isInteger(pageSize) || pageSize < 0 || pageSize > 100) {
    throw new RangeError("pageSize must be an integer from 0 to 100");
  }
  if (typeof compact !== "boolean") throw new TypeError("compact must be Boolean");
  return { theme, pageSize, layout: { compact } };
}
const input = { theme: "", pageSize: 0, layout: { compact: false } };
const before = JSON.stringify(input);
const result = buildSettings(input);
console.log(JSON.stringify(result));
console.log(JSON.stringify(buildSettings(null)));
console.log(JSON.stringify(buildSettings()));
result.layout.compact = true;
console.log(input.layout.compact, JSON.stringify(input) === before);
for (const invalid of [
  { pageSize: 101 }, { pageSize: "2" },
  { layout: { compact: "false" } }, { theme: 3 }, []
]) {
  try { buildSettings(invalid); }
  catch (error) { console.log(error.name + ": " + error.message); }
}

// ✅ Expected output:
// {"theme":"","pageSize":0,"layout":{"compact":false}}
// {"theme":"light","pageSize":20,"layout":{"compact":false}}
// {"theme":"light","pageSize":20,"layout":{"compact":false}}
// false true
// RangeError: pageSize must be an integer from 0 to 100
// RangeError: pageSize must be an integer from 0 to 100
// TypeError: compact must be Boolean
// TypeError: theme must be a string
// TypeError: settings must be an object

Practice quiz

What does this complete program print? const input = { count: 0 }; console.log(input.count || 10, input.count ?? 10);

  • 10 0
  • 0 0
  • 10 10
  • 0 10

Answer: 10 0. A rewrite from || to ?? changes the zero case. That can be intended, but it is not automatically equivalent.

What does this complete program print? const input = { title: null }; const { title = "Untitled" } = input; console.log(title, input.title ?? "Untitled");

  • Untitled Untitled
  • null Untitled
  • null null
  • Untitled null

Answer: null Untitled. A destructuring default handles undefined; the nullish fallback also handles null.

What does this complete program print? const field = "theme"; const value = "dark"; console.log(JSON.stringify({ field: value })); console.log(JSON.stringify({ [field]: value }));

  • {"theme":"dark"} {"theme":"dark"}
  • {"field":"dark"} {"field":"dark"}
  • {"field":"dark"} {"theme":"dark"}
  • {"theme":"dark"} {"field":"dark"}

Answer: {"field":"dark"} {"theme":"dark"}. The unbracketed key is literally field. The computed key evaluates the field variable.

What does this complete program print? const title = "Loops"; const record = { title }; console.log(record.title, Object.keys(record).length);

  • title 1
  • Loops 0
  • undefined 1
  • Loops 1

Answer: Loops 1. Shorthand creates the title property with the current title variable’s value.

What does this complete program print? const item = { count: 2 }; const broken = value => { count: value.count }; console.log(broken(item));

  • undefined
  • {"count":2}
  • 2
  • null

Answer: undefined. The braces form a function body with a labelled statement, and no return occurs.

What does this complete program print? const defaults = { pageSize: 20 }; const supplied = { pageSize: 0 }; console.log(JSON.stringify({ ...defaults, ...supplied }));

  • {"pageSize":20}
  • {"pageSize":0}
  • {"pageSize":null}
  • {}

Answer: {"pageSize":0}. The later supplied property wins, including its valid zero value.

What does this complete program print? const original = { layout: { compact: false } }; const copy = { ...original }; copy.layout.compact = true; console.log(original.layout.compact, original === copy);

  • false false
  • true true
  • true false
  • false true

Answer: true false. Only the outer record was copied; layout remains shared.

What does this complete program print? "use strict"; const counter = { count: 2, next() { this.count++; return this.count; } }; console.log(counter.next(), counter.count);

  • 2 2
  • 3 2
  • undefined 3
  • 3 3

Answer: 3 3. Method shorthand retains ordinary method receiver behaviour when called as counter.next().

Continue this course

Related lessons