Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Nested template literals in JavaScript

14 Nesting one template inside another

fair

Render a row per stall, where an unpaid stall shows the amount owed. Do it with one template nested inside a ternary inside another template, and no string concatenation.

Stuck? Three hints, smallest first
  1. 1. A hole may contain a ternary, and either branch may be its own template.
  2. 2. map to an array of rows, then join them with a newline inside a single hole.
  3. 3. Nesting is only an expression inside an expression — there is no depth limit and no special syntax.

The answer

const stalls = [
  { code: 'A1', owner: 'Ngozi', rentNgn: 12000, paid: true },
  { code: 'A2', owner: 'Emeka', rentNgn: 9000, paid: false },
];

const row = (s) => `${s.code}: ${s.owner} ${s.paid ? 'paid' : `owes ${s.rentNgn}`}`;
const table = `Stalls\n${stalls.map(row).join('\n')}`;

console.log(table);
console.log('---');
console.log('a hole in a template in a hole:', `${`${1 + 1}`}`);

Output


      
7 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 7 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

7 checks

test('the else branch is its own template', row(stalls[1]), 'A2: Emeka owes 9000');
test('the true branch needs no template', row(stalls[0]), 'A1: Ngozi paid');
test('the whole table is three lines', table.split('\n').length, 3);
test('the heading survives', table.split('\n')[0], 'Stalls');
test('rows keep their array order', table.split('\n')[1], 'A1: Ngozi paid');
test('nesting is just an expression, so map and join behave normally', stalls.map(row).length, 2);
test('and a template in a hole in a template in a hole is fine too', `${`${1 + 1}`}`, '2');

Nesting has no special rules, which is the point: a hole is an expression slot, and a template is an expression. Two levels reads well; three usually means the inner piece deserves a name — row here — and the outer template gets shorter as a result.

Reach for a nested template rather than + when a branch has its own text around it. s.paid ? 'paid' : 'owes ' + s.rentNgn works, but the version above keeps the quotes and the spacing in one place.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.