Skip to content

String Interpolation

Template literals allow embedding expressions directly in strings using ${} syntax, eliminating string concatenation.

const name = 'Alice';
const age = 25;
// Old way
console.log('Hello, ' + name + '! You are ' + age + '.');
// Template literal
console.log(`Hello, ${name}! You are ${age}.`);
const a = 10;
const b = 5;
// Any JavaScript expression works inside ${}
console.log(`${a} + ${b} = ${a + b}`); // '10 + 5 = 15'
console.log(`${a} > ${b}: ${a > b}`); // '10 > 5: true'
// Function calls
console.log(`Upper: ${name.toUpperCase()}`); // 'Upper: ALICE'
// Ternary operator
console.log(`${age >= 18 ? 'Adult' : 'Minor'}`);
  • ${expression} embeds any JavaScript expression
  • Expressions can include arithmetic, function calls, ternaries
  • More readable than string concatenation
  • Templates can contain other template literals