String Interpolation
String Interpolation
Section titled “String Interpolation”Introduction
Section titled “Introduction”Template literals allow embedding expressions directly in strings using ${} syntax, eliminating string concatenation.
Basic Interpolation
Section titled “Basic Interpolation”const name = 'Alice';const age = 25;
// Old wayconsole.log('Hello, ' + name + '! You are ' + age + '.');
// Template literalconsole.log(`Hello, ${name}! You are ${age}.`);Expressions
Section titled “Expressions”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 callsconsole.log(`Upper: ${name.toUpperCase()}`); // 'Upper: ALICE'
// Ternary operatorconsole.log(`${age >= 18 ? 'Adult' : 'Minor'}`);Summary
Section titled “Summary”${expression}embeds any JavaScript expression- Expressions can include arithmetic, function calls, ternaries
- More readable than string concatenation
- Templates can contain other template literals