JavaScriptFundamental (ES6), part 1
Template literals and interpolation in JavaScript
11 Template literals: interpolation
easyBuild a sentence from a name and an amount with a template literal. Then check what a template does with an object, an array, null and undefined.
Stuck? Three hints, smallest first
- 1. A hole is
${...}inside backticks, and its value is converted to a string. - 2. The conversion is the same one
String()does, which for a plain object gives[object Object]. - 3. The result of a template is always a string, whatever went into the holes.
const buyer = 'Chinedu';
const owed = 4500;
const line = `${buyer} owes NGN ${owed}`;
console.log('line :', line);
console.log('a number :', `${5}`, typeof `${5}`);
console.log('a plain object :', `${{}}`, '<- String() on an object');
console.log('an array :', `${[1, 2]}`, '<- joined with commas');
console.log('null, undefined:', `${null} and ${undefined}`);
console.log('quotes inside :', `He said "yes"`);
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('a hole is replaced by its value', line, 'Chinedu owes NGN 4500');
test('a number becomes text', `${5}`, '5');
test('a plain object goes through its toString', `${{}}`, '[object Object]');
test('an array joins with commas', `${[1, 2]}`, '1,2');
test('null and undefined print their own names', `${null} and ${undefined}`, 'null and undefined');
test('double quotes need no escaping inside backticks', `He said "yes"`, 'He said "yes"');
test('the result is always a string', typeof `${5}`, 'string');
test('a template with no holes is just a string', `plain`, 'plain');
A hole calls the same string conversion as String(x), which is why an object gives [object Object] and an array gives its join(','). If you want a readable object in a log or a message, ask for JSON.stringify explicitly; a template will not do it for you.
The practical win is quoting. A template can contain both ' and " untouched, so building an HTML attribute or a shell-ish string stops being a game of escapes.