programming:javascrip

This is an old revision of the document!


Javascript

Template literals are syntaxed ${…}

In JavaScript, strings can be written in three ways:

'string'        // single quotes
"string"        // double quotes
`string`        // backticks → template literal

Only template literals (backticks) support interpolation using: ${expression}

Inside ${…}, you can put any valid JavaScript expression:

  • variables
  • function calls
  • arithmetic
  • ternaries
  • property access

Examples

const name = 'Alex';
`Hello ${name}!`;

This produces:

Hello Alex!

Template literals can be very useful to replace long lists of 'string' + var + 'string' + var …

'Tag: ' + tag_autospawn + ' - Spawned car ' + suffix

This works, but:

  • It’s visually noisy
  • Easy to miss a space
  • Harder to refactor
  • Encourages line-breaking when long

The template literal equivalent is:

`Tag: ${tag_autospawn} - Spawned car ${suffix}`

Same result, much clearer structure.

A template literal is:

  • One string
  • With embedded expressions
  • Much easier to keep visually compact

So this: 'foo ' + a + ' bar ' + b + ' baz ' + c

Becomes: `foo ${a} bar ${b} baz ${c}`

Inside ${}, you can do more:

`UV: ${car_uv.toFixed(2)}`
 
`State: ${isActive ? 'ON' : 'OFF'}`
 
`Next index: ${pointer + 1}`

This is real code, not just substitution.

Template literals:

  • Are evaluated at runtime
  • Produce a normal string
  • Have no performance penalty compared to concatenation in modern JS engines
  • Are fully supported in ES6+ (basically everything now)

So: 'Hello ' + name

and: `Hello ${name}`

Compile down to equivalent bytecode in modern engines.

Template literals also preserve newlines exactly as written:

`Line 1
Line 2
Line 3`

This is extremely useful for logs, SQL, shaders, etc.

Template literals use backticks, not quotes

${} is not jQuery or shell syntax — it’s JS-only

Don’t confuse ${} with $(…) (shell / jQuery)

You were correct to ask — many people mix those up.

TL;DR

${…} is expression interpolation inside template literals

It replaces string concatenation cleanly

It improves readability and formatter behavior

It’s safe, modern, and efficient

It’s the idiomatic way to build strings in modern JS

If you want next, we can:

define a logging helper so you never build these strings manually again, or

talk about when not to use template literals (there are a few edge cases).

  • programming/javascrip.1769417018.txt.gz
  • Last modified: 2026/01/26 09:43
  • by mh