ā¤ Like
šŸ”– Save
šŸ”— Share
@thedevspaceio
@thedevspaceio

JavaScript Template Literals

@thedevspaceio

šŸ“ 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 ${}.

js
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.

js
const poem = `
  Roses are red,
  Violets are blue.
`;

Expression evaluation

Any valid JavaScript expression can go inside ${}.

js
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.

js
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.

js
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.

@thedevspaceio
www.thedevspace.io