๐ŸŽ“ A1Learner
๐Ÿ”

JavaScript Template Strings

A template literal is text written inside backticks. Values can sit inside the text, so a sentence can carry live data.

Values inside text

A template literal is text in backticks, and ${ } places a value inside it.

let name = "Ana";
let score = 9;
console.log(`Player ${name} scored ${score} points.`);

Expressions inside

An expression is code that produces a value. A calculation inside ${ } prints its result.

let price = 4;
let count = 3;
console.log(`Total: ${price * count}`);

Lines inside backticks

Pressing Enter inside backticks adds a newline to the text. The length count proves the newline sits inside the string as one character.

let card = `Dear Ana,
You won!`;
console.log(card.length);

Example

let item = "notebook";
let price = 6;
let count = 2;
let receipt = `${count} x ${item} = ${price * count}`;
console.log(receipt);

Key points

  • A backtick is the slanted quote mark ` on the keyboard.
  • A dollar sign and braces, written ${ }, mark a place where a value goes.
  • A template literal can span several lines, and the line breaks stay in the text.
  • Joining text with + works too, and a template literal keeps the sentence in one piece.

In this example, a template literal builds the receipt in one piece of text. The first two placeholders insert the count and the item name. The last placeholder multiplies price by count and inserts 12.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

Which pair marks where a value goes inside a template literal?