JavaScriptFundamental (ES6), part 1
Expressions inside template literals in JavaScript
12 Expressions inside a hole
easyPut real work inside the holes: arithmetic, a method call, a ternary and a nested map. Then prove the holes are evaluated once each, left to right.
Stuck? Three hints, smallest first
- 1. A hole takes any expression, not just a variable name.
- 2. To prove the order, put a function in each hole that records that it ran.
- 3. A template inside a hole is fine, and is how you build a list without string concatenation.
const cart = [
{ item: 'rice', qty: 2, priceNgn: 3200 },
{ item: 'beans', qty: 1, priceNgn: 1800 },
];
const total = cart.reduce((n, row) => n + row.qty * row.priceNgn, 0);
const seen = [];
const mark = (x) => { seen.push(x); return x; };
const built = `${mark('a')}-${mark('b')}`;
console.log('total :', `total ${total}`);
console.log('a method call :', `${cart[0].item.toUpperCase()}`);
console.log('a ternary :', `${cart.length === 1 ? 'line' : 'lines'}`);
console.log('a nested map :', `[${cart.map((r) => `${r.item} x${r.qty}`).join(', ')}]`);
console.log('holes ran in order:', seen, '->', built);
Output
8 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 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('arithmetic works inside a hole', `total ${total}`, 'total 8200');
test('so does a method call', `${cart[0].item.toUpperCase()}`, 'RICE');
test('and a ternary', `${cart.length === 1 ? 'line' : 'lines'}`, 'lines');
test('and a template inside a template', `[${cart.map((r) => `${r.item} x${r.qty}`).join(', ')}]`, '[rice x2, beans x1]');
test('holes are evaluated left to right, once each', seen, ['a', 'b']);
test('and glued together in that order', built, 'a-b');
test('an empty hole contributes nothing', `a${''}b`, 'ab');
test('a hole holds an expression, not just a name', `${1 + 2 * 3}`, '7');
Because a hole is an ordinary expression slot, a template is often the clearest way to render a list: map to strings, join with a separator, drop the result into one hole. Reaching for += in a loop instead is longer and easier to get wrong.
The evaluation-order assertion matters as soon as a hole has a side effect — a counter, a logger, something that pops off a queue. Templates evaluate strictly left to right, once per hole, so the order you read is the order that runs.