Skip to main content

String interpolation

Template literals let you embed variables and expressions directly inside strings. If you’ve used Python’s f-strings, this will feel instantly familiar.
The key difference from regular strings: template literals use backticks (`), not quotes. Variables go inside ${}.
Same concept, slightly different syntax. Backticks instead of f"...", and ${} instead of {}.

Expressions inside template literals

You can put any JavaScript expression inside ${} — math, function calls, ternary operators, method calls.
Use .toFixed(2) to format numbers as currency with exactly 2 decimal places. You’ll use this pattern constantly when displaying prices.

Multi-line strings

Template literals preserve line breaks. No need for \n characters or string concatenation.
This is much cleaner than the alternative:
Multi-line template literals preserve all whitespace, including indentation. If you indent the template literal inside a function, those spaces will appear in the output. Keep the content flush-left if spacing matters.

Building HTML strings

You’ll sometimes build HTML strings in JavaScript — especially before you learn React. Template literals make this readable.
Once you learn React in Section 7, you’ll use JSX instead of building HTML strings. But it’s useful to see this pattern first — it shows why template literals matter for web development.

Common mistakes

Template literals must use backticks (`). Single quotes '...' and double quotes "..." treat ${...} as literal text.
Python f-strings use {name}. JavaScript template literals need ${name} — don’t forget the dollar sign.

What’s next?

You can build dynamic strings. Before we move to functions, let’s cover one quick topic — comments.

Comments

Add notes and documentation to your JavaScript code