JavaScript Template Literals
š JavaScript Template Literals Cheatsheet
Template literals are strings enclosed by backticks that make it easy to embed expressions, write multiline text, and process content with tag functions.
ā Template literal features ā Interpolation ā Multiline strings ā Expression evaluation ā Tagged templates ā String.raw
#javascript #templateliterals #interpolation #backticks #taggedtemplates #strings #es6 #rawstrings #multiline #webdev
Template literals are strings enclosed in backticks (``). It enables interpolation, multiline text, and tagged templates.
Interpolation
Embed variables and expressions inside ${}.
const name = "Alice";
const age = 30;
const message = `Hello, ${name}! You are ${age} years old.`;
// "Hello, Alice! You are 30 years old."Multiline strings
Backticks preserve line breaks.
const poem = `
Roses are red,
Violets are blue.
`;Expression evaluation
Any valid JavaScript expression can go inside ${}.
const a = 5;
const b = 10;
`The sum is ${a + b}`; // "The sum is 15"
`Today is ${new Date().toDateString()}`;Tagged templates
A tag function receives the string parts and interpolated values for custom processing.
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
const value = values[i] ? `[${values[i]}]` : "";
return result + str + value;
}, "");
}
const name = "Alice";
highlight`Hello ${name}`; // "Hello [Alice]"String.raw
String.raw returns the raw string without processing escape sequences.
const raw = String.raw`line1\nline2`;
// "line1\\nline2"Full-Stack AI Developer Roadmap
From HTML & CSS to working with AI models, all in one structured roadmap.