Lesson 19 of 28
In progress
Modern syntax shortcuts worth using
Use shorthand properties, optional chaining, nullish coalescing and logical assignment to write less code without hiding intent.
JavaScript has added a lot of small syntax improvements since 2015. The good ones remove noise without hiding what the code does; the bad ones make a reader stop and decode.
What you will learn
- Write object shorthand and computed keys.
- Read optional chaining and nullish coalescing correctly.
- Use logical assignment without confusing it with comparison.
Shorthand properties and methods
Editable. Runs in your browser.
const user = { name, role, greet() { return `Hi, ${this.name}`; } };
console.log(user);
console.log(user.greet());
Press Run to see the output.
{ name } is shorthand for { name: name }. greet() {} is shorthand for greet: function () {}. Both reduce repetition, and both are now idiomatic.
Computed keys let an expression decide the property name:
Editable. Runs in your browser.
Press Run to see the output.
That is useful for building objects from dynamic data, though a Map may be clearer when every key is dynamic.
Optional chaining
?. stops evaluating when the value on its left is null or undefined, and returns undefined instead of throwing.
Editable. Runs in your browser.
console.log(user.profile?.city);
console.log(guest?.profile?.city);
console.log(user.profile?.country ?? "Unknown");
Press Run to see the output.
It is the right tool for genuinely optional data, such as an API field that may be absent. It is the wrong tool for required data that is missing because of a bug: ?. turns a loud error into a silent undefined that surfaces later.
Optional chaining also works on method calls (obj.method?.()) and array access (items?.[0]). Use the call form when the method may not exist, which happens with feature detection.
Nullish coalescing
?? returns the right side only when the left is null or undefined. Unlike ||, it keeps 0, "" and false.
Editable. Runs in your browser.
console.log(settings.volume || 10);
console.log(settings.volume ?? 10);
console.log(settings.label || "Untitled");
console.log(settings.label ?? "Untitled");
Press Run to see the output.
The first line gives 10, which is wrong if zero means muted. The second gives 0. The third replaces an intentionally empty label; the fourth keeps it. Choose based on whether the values are "missing" or "empty but valid".
Do not mix ?? and || without brackets; the language forbids it precisely because the precedence is confusing.
Logical assignment
Editable. Runs in your browser.
config.retries ??= 3;
config.name ||= "Default";
config.missing &&= "never set";
console.log(config);
Press Run to see the output.
??= assigns only when the current value is nullish. ||= assigns when the current value is falsy, so it replaces 0. &&= assigns when the current value is truthy, which is rare. These read well for defaults and badly when they hide a condition; a plain if is sometimes clearer.
Small conveniences
Editable. Runs in your browser.
console.log(big, text, entries);
Press Run to see the output.
Numeric separators make long numbers readable and do not change the value. replaceAll avoids a global regular expression for simple cases. Object.entries turns an object into pairs, which pairs naturally with map and for...of.
Array.prototype.at(-1) reads from the end, and String.prototype.at does the same for characters. Both are clearer than length - 1 once negative indexes are familiar.
Syntax that hides intent
Modern syntax is not automatically better. A nested chain of ?., ?? and a ternary is harder to read than three lines with names.
Editable. Runs in your browser.
const label = order?.customer?.name ?? "Guest";
const total = order?.total ?? 0;
console.log(`${label}: ${total}`);
Press Run to see the output.
Operator precedence adds another reason to split. a ?? b || c is a syntax error, and a ? b : c ?? d needs thought even when it parses. Two named values beat one long expression in every case where a reader has to pause and work it out. That is the rule: use shorthand to remove repetition, not to compress logic.
?? has lower precedence than most operators, so a ?? b + c is a ?? (b + c), and comparisons can surprise you. Put brackets around the nullish check when it is part of a larger expression, and never assume it behaves like ||.
Given a settings object that may be missing fields, produce a config with defaults for theme, pageSize and showHelp, where 0 and false are preserved. Use optional chaining and nullish coalescing, then log each value.
Show solution
Editable. Runs in your browser.
const config = {
theme: stored?.theme ?? "light",
pageSize: stored?.pageSize ?? 10,
showHelp: stored?.showHelp ?? true
};
console.log(config);
Press Run to see the output.
The zero page size survives because the fallback is nullish, not falsy. Missing fields get their defaults, and the code says exactly which values are optional.
Recap
- Object shorthand and computed keys remove repetition in literals.
?.and??handle missing data; they should not hide bugs in required data.- Logical assignment is concise, but a plain
ifis clearer when a condition is involved.
Next, you will pull values apart with destructuring and combine them with spread.
Can I use optional chaining on the left of an assignment?
Is ?? supported everywhere?
Progress is saved in this browser only. No account, no email.