JavaScript Template Literals Advanced (Tagged Templates) Quiz

JavaScript
0 Passed
0% acceptance

Answer 35 questions digging into template literal basics, tagged function mechanics, string/value processing, security sanitization, custom formatting, localization, DSL construction, and performance trade-offs.

35 Questions
~70 minutes
1

Question 1

Which feature do template literals add beyond single or double quotes?

A
Embedded expressions using ${...}
B
Automatic deep cloning
C
Synchronous HTTP requests
D
Implicit JSON parsing
2

Question 2

Why are template literals convenient for multi-line strings?

A
Backticks preserve newlines without escape characters
B
They automatically trim whitespace
C
They convert strings to numbers
D
They enforce indentation
3

Question 3

What logs?

javascript
const user = 'Nia'
console.log(`Hello, ${user}!`)
A
Hello, Nia!
B
${user}
C
Hello, ${user}!
D
undefined
4

Question 4

What is a tagged template literal?

A
A template string processed by a custom function before evaluation
B
A string that automatically becomes HTML
C
A literal that loads external scripts
D
A deprecated syntax
5

Question 5

What arguments does a tag function receive?

A
An array of string segments plus the interpolated values as rest arguments
B
Only the interpolated values
C
Only cooked strings, never raw forms
D
No arguments; tags use globals
6

Question 6

What logs?

javascript
function tag(strings, value) {
  console.log(strings[0], value)
}
const amount = 5
tag`Items: ${amount}`
A
'Items: ' 5
B
'Items: ${amount}'
C
5 Items:
D
undefined undefined
7

Question 7

Which property exposes unescaped characters inside a tag?

A
strings.raw
B
strings.clean
C
strings.literal
D
strings.meta
8

Question 8

Why should tag functions treat strings as immutable?

A
Mutating the passed array can break sharing across repeated calls
B
Mutating strings accelerates performance
C
Strings are passed by reference to server
D
Tags forbid rest parameters
9

Question 9

What logs?

javascript
function repeatTag(strings, value) {
  return `${strings[0]}${value}${value}`
}
console.log(repeatTag`Value: ${3}`)
A
Value: 33
B
Value: 3
C
Value: ${3}${3}
D
33Value:
10

Question 10

Why can tag functions return non-string values?

A
Tagged templates are just function calls; the return value is whatever the function returns
B
Because template literals always convert to arrays
C
Because tags modify the compiler
D
Because tags only run during build time
11

Question 11

What logs?

javascript
const toObject = (strings, ...values) => ({ strings, values })
const result = toObject`A ${1} B ${2}`
console.log(result.values)
console.log(result.strings.length)
A
[1, 2] and 3
B
['A ', ' B ', ''] and 2
C
[1] and 2
D
Throws TypeError
12

Question 12

How does a tag differentiate between segments and values when reconstructing output?

A
By iterating strings and interleaving with values at each gap
B
By calling eval internally
C
By reading from a shared global buffer
D
By mutating the template literal inline
13

Question 13

Why are tagged templates popular for HTML sanitization?

A
Tags can escape untrusted values before concatenating into markup
B
Tags disable JavaScript entirely
C
Tags automatically encode CSS
D
Tags run only on the server
14

Question 14

What logs?

javascript
const escapeHTML = (strings, ...values) => strings.reduce((out, str, i) => {
  const val = values[i] ?? ''
  return out + str + val.replace?.(/[<>&"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c])) ?? val
}, '')
const unsafe = '<script>1</script>'
console.log(escapeHTML`Safe: ${unsafe}`)
A
Safe: &lt;script&gt;1&lt;/script&gt;
B
Safe: <script>1</script>
C
<script>1</script>
D
undefined
15

Question 15

Why should security tags carefully handle non-string values?

A
Because numbers, booleans, or objects may require conversion or special handling to avoid injection
B
Because non-strings cannot exist inside template literals
C
Because JSON stringify is automatic
D
Because tags only run in browsers
16

Question 16

Which practice strengthens sanitized tagged templates?

A
Return a trusted wrapper type (e.g., object with toString) instead of plain strings to avoid accidental unsanitized concatenation
B
Store sanitized strings globally
C
Disable template literals
D
Use eval inside the tag
17

Question 17

What logs?

javascript
const currency = (strings, value) => `${strings[0]}$${value.toFixed(2)}`
console.log(currency`Price: ${4.5}`)
A
Price: $4.50
B
Price: 4.5
C
$4.5
D
undefined
18

Question 18

How do tagged templates simplify custom string builders?

A
They let you reuse the same helper across many strings with consistent formatting rules
B
They modify the language grammar
C
They forbid regular expressions
D
They automatically memoize results
19

Question 19

What logs?

javascript
function pad(strings, value, width = 4) {
  const num = String(value)
  return `${strings[0]}${num.padStart(width, '0')}`
}
console.log(pad`ID: ${42}`)
A
ID: 0042
B
ID: 42
C
0042
D
Throws TypeError
20

Question 20

Why can tagged templates improve readability in logging utilities?

A
They enforce consistent structure and support metadata injection without manual concatenation
B
They automatically send logs to remote servers
C
They disable string interpolation
D
They convert logs into JSON automatically
21

Question 21

Why are tagged templates useful for localization?

A
Tags can reorder placeholders and apply locale-aware formatting before returning the string
B
They automatically translate text based on geolocation
C
They embed multiple languages simultaneously
D
They force browsers to download dictionaries
22

Question 22

What logs?

javascript
const i18n = (strings, ...values) => strings.reduce((acc, part, i) => acc + part + (values[i]?.toLocaleString?.('de-DE') ?? values[i] ?? ''), '')
console.log(i18n`Total: ${1234.5}`)
A
Total: 1.234,5
B
Total: 1234.5
C
1.234,5 Total:
D
undefined
23

Question 23

How can localization tags handle pluralization?

A
Inspect numeric values, choose singular/plural string segments, and assemble the final sentence accordingly
B
Automatically detect the user’s keyboard layout
C
Insert CSS rules
D
Modify HTTP headers
24

Question 24

Why should localized tags avoid concatenating raw user input?

A
They must escape or validate inputs to prevent injection and maintain consistent encoding
B
Localization automatically encodes data
C
Browsers forbid user input inside templates
D
Tags execute only on the server
25

Question 25

What is a DSL (domain-specific language) in the context of tagged templates?

A
A mini-language encoded within template syntax that a tag interprets into structured data or commands
B
A built-in browser API for CSS
C
A type of JSON parser
D
A low-level hardware instruction set
26

Question 26

What logs?

javascript
const sql = (strings, ...values) => ({
  text: strings.reduce((acc, part, i) => acc + part + (values[i] ? '$' + (i + 1) : ''), ''),
  values
})
const query = sql`SELECT * FROM users WHERE id = ${7}`
console.log(query.text)
console.log(query.values)
A
'SELECT * FROM users WHERE id = $1' and [7]
B
'SELECT * FROM users WHERE id = 7' and []
C
'SELECT * FROM users WHERE id = ?' and [7]
D
Throws TypeError
27

Question 27

Why should DSL tags validate their input segments?

A
To ensure the DSL syntax is correct and to prevent injection or misinterpretation of commands
B
To speed up garbage collection
C
To auto-generate TypeScript declarations
D
To detect user locale
28

Question 28

What logs?

javascript
const css = (strings, ...values) => strings.reduce((out, str, i) => out + str + (values[i] ?? ''), '').trim()
console.log(css`
  color: ${'red'};
  font-weight: ${'bold'};
`)
A
color: red; font-weight: bold;
B
color: ${'red'}; font-weight: ${'bold'};
C
undefined
D
Throws TypeError
29

Question 29

Why can tagged templates be slower than plain template literals?

A
Each invocation calls a function and may perform additional parsing or allocations
B
Tagged templates require network requests
C
Tagged templates disable JIT compilation
D
They convert strings to binary
30

Question 30

What logs?

javascript
let calls = 0
const countTag = (strings, ...values) => {
  calls += 1
  return strings.join('') + values.join('')
}
countTag`A ${1}`
countTag`B ${2}`
console.log(calls)
A
2
B
1
C
0
D
undefined
31

Question 31

How can developers mitigate tagged template overhead?

A
Memoize heavy tag operations or precompile DSL templates where possible
B
Use eval inside tags
C
Avoid template literals entirely
D
Invoke garbage collection manually
32

Question 32

Why should large tagged templates avoid allocating new arrays each run?

A
Template string arrays are reused by the engine, so reusing structures in tags prevents extra garbage
B
Allocations make template literals invalid
C
Arrays cannot exist inside tags
D
Engines ban arrays in strict mode
33

Question 33

What logs?

javascript
const highlight = (strings, ...values) => strings.reduce((out, str, i) => out + str + (values[i] ? `<mark>${values[i]}</mark>` : ''), '')
console.log(highlight`Result: ${'OK'}!`)
A
Result: <mark>OK</mark>!
B
Result: OK!
C
<mark>Result:</mark> OK!
D
undefined
34

Question 34

Why should performance-sensitive tags avoid heavy regex work per call?

A
Expensive regex operations inside frequently executed tags can become bottlenecks
B
Regex is incompatible with template literals
C
Regex automatically memoizes results
D
Regex converts tags to generators
35

Question 35

When are tagged templates most compelling?

A
When you need declarative syntax with custom processing, such as sanitization, localization, or DSL parsing
B
When you want to disable template literals
C
When you must perform synchronous I/O
D
When you need to enforce type checking in plain JS

QUIZZES IN JavaScript