ā¤ Like
šŸ”– Save
šŸ”— Share
Eric Hu
Eric Hu

JavaScript Template Literals

@thedevspaceio

šŸ“ Backtick Strings in JavaScript Should Have Been the Default

Think about it: multiline strings without \n; embedded variables without +; dynamic content without escaping hell.

Template literals do all of this. Yet people still instinctively go for single and double quotes when creating strings.

What if backticks had been the default from the start?

āœ… 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