0Pricing
Frontend Academy · Lesson

Template Literals and Optional Chaining

Embed expressions in strings with template literals, safely access nested properties with ?., and short-circuit with the nullish coalescing operator ??.

Template Literals and Optional Chaining is a free Frontend Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Frontend Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Template Literals: Backtick Strings

Template literals (backtick strings) support multi-line strings and embedded expressions. They replace string concatenation with + and make intent clearer.

// String concatenation (old way):
const msg = 'Hello, ' + name + '! You have ' + count + ' messages.';

// Template literal (modern):
const msg2 = `Hello, ${name}! You have ${count} messages.`;

Multi-line Template Literals

Template literals preserve newlines and indentation. No more \n or string concatenation across multiple lines.

const html = `
  <div class="card">
    <h2>${title}</h2>
    <p>${body}</p>
  </div>
`;

const sql = `
  SELECT *
  FROM users
  WHERE age > ${minAge}
  ORDER BY name
`;

Expressions in Template Literals

Any JavaScript expression can go inside ${}: ternaries, function calls, arithmetic, method calls.

const tax = 0.2;
const price = 50;
const receipt = `
  Subtotal: $${price}
  Tax (${tax * 100}%): $${price * tax}
  Total: $${price * (1 + tax)}
  ${isPaid ? 'PAID' : 'UNPAID'}
`;

Tagged Template Literals

A tagged template calls a function with the string parts and interpolated values as arguments. Used by libraries like styled-components, GraphQL (gql``), and sql`` for safe query building.

function highlight(strings, ...values) {
  return strings.reduce((acc, str, i) =>
    acc + str + (values[i] !== undefined ? `<mark>${values[i]}</mark>` : ''), '');
}
const msg = highlight`Hello ${name}, you have ${count} messages.`;

Optional Chaining: ?.

The optional chaining operator ?. short-circuits to undefined instead of throwing a TypeError if the left side is null or undefined. Eliminates defensive null checks.

const user = null;

// Without optional chaining (throws TypeError):
// user.profile.avatar

// With optional chaining (returns undefined):
const avatar = user?.profile?.avatar;
console.log(avatar); // undefined — no error

Optional Method Calls

obj?.method() calls the method only if obj is not null/undefined. If obj is null, it returns undefined without throwing.

const timer = getTimer(); // might return null
timer?.start(); // only calls start() if timer exists

// Also works on array access:
const firstItem = arr?.[0]; // undefined if arr is null

Nullish Coalescing: ??

The nullish coalescing operator ?? returns the right-hand side only if the left is null or undefined (not falsy). Unlike ||, it doesn't treat 0 or '' as nullish.

const port = config.port ?? 3000;  // 3000 only if port is null/undefined
const name = user.name ?? 'Anonymous';

// Compare with ||:
console.log(0 ?? 'default');   // 0 (not nullish)
console.log(0 || 'default');   // 'default' (falsy!)

Nullish Assignment: ??=

a ??= b assigns b to a only if a is null or undefined. Shorthand for a = a ?? b. Useful for initialising object properties conditionally.

let cache = {};
function getUser(id) {
  cache[id] ??= fetchUser(id); // only fetch if not cached
  return cache[id];
}

Logical Assignment Operators

&&= assigns only if the left is truthy. ||= assigns only if the left is falsy. Together with ??=, these make conditional assignments concise.

user.name ||= 'Anonymous';  // set if falsy
user.role &&= user.role.toLowerCase(); // transform if exists

Combining ?. and ??

Combine optional chaining and nullish coalescing for safe property access with a default value.

const city = user?.address?.city ?? 'Unknown';
const total = cart?.items?.length ?? 0;

String Methods You Need to Know

Common string methods: trim(), trimStart(), trimEnd(), padStart(), padEnd(), startsWith(), endsWith(), includes(), replaceAll(), at().

const str = '  Hello World  ';
str.trim();           // 'Hello World'
str.includes('World'); // true
'5'.padStart(3, '0'); // '005'
'abc'.at(-1);         // 'c'
'aabbcc'.replaceAll('b', 'x'); // 'aaxxcc'

Quick Check

What does const val = obj?.foo?.bar ?? 'default' return if obj is null?

Recap: Template Literals and Optional Chaining

Backtick strings support expressions and multiline. Tagged templates enable DSLs. ?. safely accesses properties without null checks. ?? provides a default when the value is null/undefined (not just falsy). Combine them for safe, readable data access with defaults.

Frequently asked questions

Is the “Template Literals and Optional Chaining” lesson free?

Yes — the full text of “Template Literals and Optional Chaining” is free to read here on the web, and the Frontend Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Frontend Academy course, upgrade to CoddyKit PRO.

What will I learn in “Template Literals and Optional Chaining”?

Embed expressions in strings with template literals, safely access nested properties with ?., and short-circuit with the nullish coalescing operator ??. You practise Frontend Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Frontend Academy?

No prior experience is required. Frontend Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Template Literals and Optional Chaining” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Frontend Academy lesson?

Yes. Every Frontend Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Array Methods: map filter reduce find
  2. Object Destructuring and Spread
  3. Template Literals and Optional Chaining
  4. Modules: import and export
← Back to Frontend Academy