shou2017.com
JP

JavaScript: What are Template Literals

Sun Jan 6, 2019
Sat Aug 10, 2024

Template literals are a more convenient way to write strings compared to the previous ES5 syntax.

They are also sometimes called template strings.

The ES5 way of writing:

function getMessage() {
  const year = new Date().getFullYear();
  return "This year is " + year +" year."
}

getMessage();

Writing with template literals:

Use `` (backticks) with $ and {}.

It’s similar to Ruby’s string interpolation #{}.

function getMessage() {
  const year = new Date().getFullYear();
  return `This year is ${year}.`
}

getMessage();

When to use:

  • Makes data more readable
  • Be careful not to overuse as it can make code less clear

改訂新版JavaScript本格入門 ~モダンスタイルによる基礎から現場での応用まで

See Also