Skip to content

Modern JavaScript syntax: functions, nulls, classes

ECMAScript 2015 and the editions after it changed how everyday JavaScript reads. Code that once needed var self = this, options = options || {} and chains of if (a && a.b && a.b.c) now uses arrow functions, default parameters, destructuring, optional chaining and nullish coalescing. This page explains those core syntax features together, because real code uses them together: a function that takes an options object usually destructures it with defaults, reads nested data with ?. and falls back with ??. It ends with classes, the syntax most application models are written in.

Each section gives the edition, the rules that matter in practice, one runnable sample and the pitfalls. For deeper single-feature pages, follow the reading path at the end.

Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). ES modules always run in strict mode. The output shown under each sample was produced with Node.js 22.23.

Feature Edition Use it when
Arrow functions ES2015 You write a callback or a short function that should use the surrounding this.
Default parameters ES2015 A parameter has a sensible value when the caller leaves it out.
Destructuring ES2015 You need several values from an object or array, or named options.
Template literals ES2015 You build strings from values, multi-line text, or need a tagged template.
Optional chaining ES2020 You read through a value that may be null or undefined.
Nullish coalescing ES2020 You need a default only when a value is missing, keeping 0 and "".
Classes ES2015, fields ES2022 You model objects with shared behavior, state and inheritance.

Introduced in ECMAScript 2015. An arrow function is a compact function expression: (a, b) => a + b. With a single parameter the parentheses are optional, and with an expression body the value is returned implicitly. A block body => { ... } needs an explicit return, and an object literal body must be wrapped in parentheses, () => ({ id: 1 }), or the braces are read as a block.

The important difference is not length but binding. Arrow functions have no own this, arguments, super or new.target; they use the ones from the enclosing scope. That makes them the right choice for callbacks inside methods, where a regular function would get its own this and lose the object. It also means call, apply and bind cannot change their this.

Arrow functions cannot be used with new (calling one as a constructor throws a TypeError), have no prototype property and cannot be generators. They are not anonymous in practice: const total = () => 0 gets the name "total" by name inference, which appears in stack traces.

class OrderList {
constructor(orders) {
this.orders = orders;
this.currency = "EUR";
}
labels() {
// The arrow callback uses this from labels(), so this.currency works.
return this.orders.map((order) => `${order.id}: ${order.total} ${this.currency}`);
}
labelsWithFunction() {
return this.orders.map(function (order) {
return `${order.id}: ${typeof this}`; // a regular callback gets its own this
});
}
}
const list = new OrderList([{ id: "A-1001", total: 37 }, { id: "A-1002", total: 120 }]);
console.log(list.labels());
console.log(list.labelsWithFunction());
const toSummary = (order) => ({ id: order.id, large: order.total >= 100 });
console.log(list.orders.map(toSummary), toSummary.name);
const sumAll = (...amounts) => amounts.reduce((sum, n) => sum + n, 0);
console.log(sumAll(10, 20, 7));
try {
new toSummary();
} catch (error) {
console.log(error.name + ":", error.message);
}

Output:

[ 'A-1001: 37 EUR', 'A-1002: 120 EUR' ]
[ 'A-1001: undefined', 'A-1002: undefined' ]
[ { id: 'A-1001', large: false }, { id: 'A-1002', large: true } ] toSummary
37
TypeError: toSummary is not a constructor

Pitfalls:

  • Arrow functions as object methods. { total: () => this.lines } does not see the object. Use method shorthand total() {}.
  • Returning an object literal without parentheses. () => { id: 1 } returns undefined; write () => ({ id: 1 }).
  • Using arguments. Arrows read the enclosing function’s arguments, or throw a ReferenceError at module level. Use a rest parameter.

Introduced in ECMAScript 2015. A default value is written in the parameter list, function ship(order, method = "standard"), and is used when the argument is missing or is exactly undefined. Passing null, 0, false or "" keeps that value. This fixes the old method = method || "standard" idiom, which replaced every falsy argument.

Defaults are expressions evaluated at call time, left to right, every time the default is needed. A default can therefore create a fresh object or array per call, call a function, or refer to earlier parameters: function range(start, end = start + 10). Referring to a later parameter throws a ReferenceError, because parameters have their own temporal dead zone.

Defaults combine with destructuring for options objects: function search({ page = 1, pageSize = 20 } = {}). The = {} at the end lets callers omit the whole object. A function’s length counts only the parameters before the first one with a default, which matters to libraries that inspect arity.

let nextId = 1000;
const newId = () => `A-${++nextId}`;
function createOrder(customer, lines = [], { express = false, notes = null } = {}, id = newId()) {
return { id, customer, lines, express, notes };
}
console.log(createOrder("ana@example.test"));
console.log(createOrder("ben@example.test", undefined, { express: true }));
console.log(createOrder("cy@example.test", [{ sku: "MUG-01" }], { notes: "" }, "A-9999"));
const first = createOrder("a@example.test");
const second = createOrder("b@example.test");
console.log("fresh array per call:", first.lines !== second.lines);
function discount(total, rate = 0.1, max = total * rate) {
return Math.min(total * rate, max);
}
console.log(discount(200), discount(200, 0.5, 30), discount(200, null)); // null is kept: total * null is 0
console.log("length:", createOrder.length, discount.length);

Output:

{
id: 'A-1001',
customer: 'ana@example.test',
lines: [],
express: false,
notes: null
}
{
id: 'A-1002',
customer: 'ben@example.test',
lines: [],
express: true,
notes: null
}
{
id: 'A-9999',
customer: 'cy@example.test',
lines: [ { sku: 'MUG-01' } ],
express: false,
notes: ''
}
fresh array per call: true
20 30 0
length: 1 1

Pitfalls:

  • Expecting null to trigger the default. Only undefined does. Normalize with value ?? fallback if callers send null.
  • Forgetting = {} after a destructured parameter. Calling search() then throws because undefined cannot be destructured.
  • Side effects in defaults. A default such as id = newId() runs on every call that omits it, which is intended here but surprising if the function has a cost.

Introduced in ECMAScript 2015. Destructuring unpacks values from arrays and properties from objects into variables with a pattern that mirrors the data. Object patterns match by property name: const { id, total } = order. You can rename ({ id: orderId }), add defaults ({ currency = "EUR" }), go into nested objects and collect the remaining properties with rest ({ id, ...details }, ES2018). Array patterns match by position: const [first, , third] = items, and they work with any iterable, such as a Map entry or a string.

Defaults apply only when the value is undefined, the same rule as default parameters. Destructuring null or undefined itself throws a TypeError, so give fallbacks to values that may be missing.

Destructuring is especially useful in parameters, where it documents which fields a function uses, and in for...of loops over Object.entries() or a Map. Swapping two variables is [a, b] = [b, a]. When you destructure into existing variables with an object pattern, wrap the statement in parentheses: ({ a, b } = obj);, or the braces are read as a block.

const order = {
id: "A-1001",
customer: { name: "Ana Silva", address: { city: "Lisbon" } },
lines: [
{ sku: "MUG-01", qty: 2 },
{ sku: "TEE-03", qty: 1 },
],
status: undefined,
};
const {
id: orderId,
customer: {
name,
address: { city, country = "PT" },
},
status = "pending",
...rest
} = order;
console.log(orderId, name, city, country, status, Object.keys(rest));
const [firstLine, ...otherLines] = order.lines;
console.log(firstLine.sku, otherLines.length);
function formatLine({ sku, qty = 1 }, index) {
return `${index + 1}. ${sku} x${qty}`;
}
console.log(order.lines.map(formatLine));
const stock = new Map([["MUG-01", 14], ["TEE-03", 0]]);
for (const [sku, units] of stock) {
console.log(sku, units > 0 ? "in stock" : "sold out");
}
let primary = "card";
let backup = "invoice";
[primary, backup] = [backup, primary];
console.log(primary, backup);
try {
const { email } = null;
} catch (error) {
console.log(error.name + ":", error.message);
}

Output:

A-1001 Ana Silva Lisbon PT pending [ 'lines' ]
MUG-01 1
[ '1. MUG-01 x2', '2. TEE-03 x1' ]
MUG-01 in stock
TEE-03 sold out
invoice card
TypeError: Cannot destructure property 'email' of 'null' as it is null.

Pitfalls:

  • Destructuring a value that may be missing. const { a } = maybeNull throws. Write = maybeNull ?? {}.
  • Deep patterns that hide the data shape. Three levels of nesting in one pattern is hard to read; destructure in steps.
  • Renaming syntax confusion. { id: orderId } creates orderId, not id. The left side is the property, the right side is the new name.

Introduced in ECMAScript 2015. A template literal is a string written with backticks. It can contain line breaks directly and embeds expressions with ${expression}; each value is converted with the same rules as String(value), so objects become "[object Object]" unless they define toString, and a symbol throws a TypeError. Whitespace and line breaks inside the backticks are kept exactly, including indentation.

A tagged template puts a function name before the literal: sql`SELECT ...`. The function receives the array of literal string parts and the evaluated values separately, so it can escape, translate or validate values before combining them. The strings array also has a raw property with the text before escape processing; the built-in tag String.raw returns that raw text, which is handy for Windows paths and regular expression sources. Since ES2018, tagged templates accept escape sequences that are invalid in normal strings, giving undefined for the cooked value.

Template literals do not escape anything by themselves. Interpolating user input into HTML or SQL is still an injection risk; use a tag function or, better, the safe APIs of your framework or database driver.

const order = { id: "A-1001", customer: "Ana <ana@example.test>", total: 37, lines: 2 };
const summary = `Order ${order.id}: ${order.lines} line${order.lines === 1 ? "" : "s"}, total ${order.total.toFixed(2)} EUR`;
console.log(summary);
const email = `Hello,
your order ${order.id} has shipped.`;
console.log(email.split("\n").length, "lines");
function html(strings, ...values) {
const escape = (value) =>
String(value).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
return strings.reduce((out, part, i) => out + part + (i < values.length ? escape(values[i]) : ""), "");
}
console.log(html`<td>${order.customer}</td>`);
console.log(String.raw`C:\orders\new`, "|", `${{}}`);

Output:

Order A-1001: 2 lines, total 37.00 EUR
3 lines
<td>Ana &lt;ana@example.test&gt;</td>
C:\orders\new | [object Object]

Pitfalls:

  • Treating interpolation as escaping. `<p>${userInput}</p>` is not safe HTML. Escape, or let a framework render text.
  • Unwanted indentation. Lines inside an indented template keep their leading spaces. Build multi-line text from an array with join("\n") when layout matters.
  • Interpolating objects. ${order} gives [object Object]. Interpolate fields or JSON.stringify(order).

Introduced in ECMAScript 2020. The optional chaining operator ?. reads a property, element or call only if the value before it is not null or undefined. If it is, the whole expression short-circuits and evaluates to undefined instead of throwing a TypeError. There are three forms: obj?.prop, obj?.[key] and fn?.(args).

Short-circuiting covers the rest of the chain: in order.customer?.address.city, if customer is missing nothing after ?. is evaluated, so you do not need ?. at every step, only where a value can legitimately be absent. Arguments in a skipped call are not evaluated either.

The call form fn?.() checks only for null or undefined; if fn is some other non-function value, the call still throws. Optional chaining cannot be used on the left side of an assignment (order.customer?.email = x is a SyntaxError), with new, or as a template tag. It pairs naturally with ?? to supply a default: order.customer?.address?.city ?? "unknown".

const orders = [
{ id: "A-1001", customer: { name: "Ana", address: { city: "Lisbon" } }, notify: (msg) => `sent: ${msg}` },
{ id: "A-1002", customer: { name: "Ben" } },
{ id: "A-1003", customer: null },
];
for (const order of orders) {
const city = order.customer?.address?.city ?? "no address";
const firstLetter = order.customer?.name?.[0];
const notified = order.notify?.(`order ${order.id} shipped`) ?? "no notifier";
console.log(order.id, city, firstLetter, notified);
}
let calls = 0;
const missing = null;
missing?.method(calls++); // the argument is not evaluated
console.log("calls:", calls);
try {
const broken = { notify: "yes" };
broken.notify?.("hi");
} catch (error) {
console.log(error.name + ":", error.message);
}

Output:

A-1001 Lisbon A sent: order A-1001 shipped
A-1002 no address B no notifier
A-1003 no address undefined no notifier
calls: 0
TypeError: broken.notify is not a function

Pitfalls:

  • Hiding bugs with ?. everywhere. If an order must always have a customer, a TypeError is useful. Use ?. only where absence is a valid state.
  • Assigning through ?.. It is a syntax error. Check first: if (order.customer) order.customer.email = value;.
  • Expecting ?.() to check the type. It guards only against null and undefined, not against a value that is not a function.

Introduced in ECMAScript 2020. The nullish coalescing operator a ?? b returns a unless it is null or undefined, in which case it returns b. Like ||, it short-circuits: b is evaluated only when needed. Unlike ||, it keeps every other falsy value, so 0, "", false and NaN are treated as real data. That makes ?? the right default operator for quantities, prices, page sizes, flags and strings where empty is meaningful.

?? has lower precedence than || and &&, and the grammar forbids mixing them without parentheses: a || b ?? c is a SyntaxError. Write (a || b) ?? c to make the intent explicit. Its assignment form, x ??= value (ES2021), assigns only when x is null or undefined, which is a concise way to initialize missing settings or caches.

A useful rule: use ?? when the question is “is this value missing?”, and || when the question is “is this value empty or falsy?”.

const settings = { pageSize: 0, currency: "", showTax: false, theme: null };
console.log("pageSize ||:", settings.pageSize || 25, "| ??:", settings.pageSize ?? 25);
console.log("currency ||:", JSON.stringify(settings.currency || "EUR"), "| ??:", JSON.stringify(settings.currency ?? "EUR"));
console.log("showTax ||:", settings.showTax || true, "| ??:", settings.showTax ?? true);
console.log("theme ??:", settings.theme ?? "light", "| missing ??:", settings.locale ?? "en-US");
let evaluated = false;
const fallback = () => {
evaluated = true;
return 10;
};
const qty = 3 ?? fallback();
console.log("qty:", qty, "fallback evaluated:", evaluated);
settings.theme ??= "dark";
settings.pageSize ??= 50;
console.log(settings.theme, settings.pageSize);
try {
new Function("a", "b", "c", "return a || b ?? c");
} catch (error) {
console.log(error.name + ":", error.message);
}
console.log((null || undefined) ?? "parenthesized is fine");

Output:

pageSize ||: 25 | ??: 0
currency ||: "EUR" | ??: ""
showTax ||: true | ??: false
theme ??: light | missing ??: en-US
qty: 3 fallback evaluated: false
dark 0
SyntaxError: Unexpected token '??'
parenthesized is fine

Pitfalls:

  • Replacing every || mechanically. Some code really wants “empty means default”, for example a blank display name. Decide per case.
  • Mixing ?? with || or && without parentheses. It does not parse. Add parentheses.
  • Expecting ?? to catch NaN or empty strings from parsing. Number("abc") ?? 0 is still NaN. Validate parsed values separately.

Introduced in ECMAScript 2015; public and private fields, private methods and static blocks were added in ECMAScript 2022. A class declares a constructor, methods and, with extends, a parent class. It is syntax over JavaScript’s prototype model: methods live on ClassName.prototype and are shared by all instances, and extends links prototypes. See Prototypes for the underlying mechanism.

Rules worth knowing:

  • Class bodies always run in strict mode, and class methods are non-enumerable.
  • Class declarations are hoisted but stay in the temporal dead zone until their line runs, so you cannot use a class before its declaration.
  • A class must be called with new; calling it as a function throws a TypeError.
  • In a subclass constructor you must call super(...) before using this.
  • Fields (status = "pending") are created on each instance before the constructor body runs (in a subclass, right after super() returns). Private members start with # and are inaccessible outside the class body; static members belong to the class itself.
  • Getters and setters (get total()) define computed properties.
class Order {
static #count = 0;
#lines = [];
status = "pending";
constructor(id) {
this.id = id;
Order.#count++;
}
add(sku, price, qty = 1) {
this.#lines.push({ sku, price, qty });
return this; // allows chaining
}
get total() {
return this.#lines.reduce((sum, line) => sum + line.price * line.qty, 0);
}
static get created() {
return Order.#count;
}
toString() {
return `${this.id} (${this.status}): ${this.total.toFixed(2)}`;
}
}
class GiftOrder extends Order {
constructor(id, message) {
super(id); // must come before using this
this.message = message;
}
get total() {
return super.total + 3; // gift wrapping
}
}
const order = new Order("A-1001").add("MUG-01", 9.5, 2).add("TEE-03", 18);
const gift = new GiftOrder("A-1002", "Happy birthday").add("CAP-07", 12);
console.log(String(order), "|", String(gift));
console.log(Object.keys(gift), Order.created, gift instanceof Order);
console.log("#lines in order:", Object.hasOwn(order, "#lines"), "| methods enumerable:", Object.keys(Order.prototype));
try {
Order("A-1003");
} catch (error) {
console.log(error.name + ":", error.message);
}

Output:

A-1001 (pending): 37.00 | A-1002 (pending): 15.00
[ 'status', 'id', 'message' ] 2 true
#lines in order: false | methods enumerable: []
TypeError: Class constructor Order cannot be invoked without 'new'

Pitfalls:

  • Passing methods as callbacks. button.onclick = order.submit loses this. Use an arrow wrapper, bind, or an arrow-function field.
  • Deep inheritance trees. Each level couples subclasses to parent internals. Prefer composition (an order has a pricing strategy) over long extends chains.
  • Expecting underscore names to be private. _lines is only a convention. Use #lines for real privacy.
Old pattern Modern replacement
var self = this in callbacks Arrow function
A falsy check that assigns a default inside the function body Default parameter, or ??
var a = obj.a; var b = obj.b; Destructuring
"Order " + id + ": " + total Template literal
a && a.b && a.b.c a?.b?.c
value !== null && value !== undefined ? value : fallback value ?? fallback
Constructor function plus prototype assignments class

1. What does an arrow function not have, compared with a regular function? Its own this, arguments, super and new.target, and a prototype. It cannot be called with new or be a generator. Those values come from the enclosing scope, which is why arrows suit callbacks inside methods.

2. When is a default parameter used, and when is it evaluated? When the argument is missing or undefined (not null). The default expression is evaluated at call time, every time it is needed, and can refer to earlier parameters.

3. What is the difference between a || b and a ?? b, and why can you not write a || b ?? c? || falls back for any falsy value; ?? only for null and undefined. Mixing them without parentheses is a syntax error by design, so the reader is never unsure which operator applies first.

4. What does order.customer?.address.city return when customer is null, and does it throw when address is missing? It returns undefined, because ?. short-circuits the rest of the chain. If customer exists but address is missing, .city is read on undefined and throws; add ?. at each step where absence is valid.

5. Are JavaScript classes different from prototypes? No. A class creates a constructor function whose prototype holds the methods, and extends links prototype chains. Classes add strict mode, a required new, non-enumerable methods, super, fields and real private members (#).

6. Senior scenario: a pricing service accepts function quote({ qty, discount } = {}) and computes const rate = discount || 0.05. Finance reports that orders with a negotiated 0% discount are billed with 5%. How do you fix it, and how do you prevent the class of bug? 0 is falsy, so || replaces it. Use a destructuring default ({ discount = 0.05 }) or discount ?? 0.05, which keep 0. To prevent recurrence, validate inputs at the boundary (a schema that requires numbers in range), add tests for zero and empty values, and use a lint rule that flags || defaults on numeric fields, such as typescript-eslint’s prefer-nullish-coalescing.

Read the sections above first, then go deeper in this order:

  1. Block bindings: let, const, block scope and the temporal dead zone.
  2. Object shorthand and Computed property names: the object literal improvements that pair with destructuring.
  3. Rest/spread properties: copying, merging and omitting, plus array spread and rest parameters.
  4. Logical assignment: ||=, &&= and ??=.
  5. Private fields, Private methods and Static blocks: the ES2022 class features.
  6. Exponentiation operator, Numeric separators and Trailing commas: small syntax features.