What are Template literals (Template strings) in JS?

JavaScript: What are Template literals (Template strings) in JS?

Template literals are string literals which let you include some expressions. You can also use them for multi line strings. Before ES2015 they were known as Template Strings, but now they're called Template Literals.

To use them, use the backtick (probably next to your left shift key, or next to your 1 key): ` ... `.

You can use the ${variable_name} format to put values into the string:

Here is an example:

  1. let name = "Microsoft";
  2. let sector = "IT";
  3. let country = "USA";
  4.  
  5.  
  6. console.log(`
  7. Hello, this is a string (multi line).
  8.  
  9. ${name} is a ${sector} company, based in ${country}
  10.  
  11. `);

Hello, this is a string (multi line).

Microsoft is a IT company, based in USA

You can also put expressions like this:

  1. console.log(`The answer to your question is: ${50+12}`);

The answer to your question is: 62

And even things like functions:

  1. function webdevetc_url() { return "https://webdevetc.com/"; }
  2.  
  3. console.log(`The url is ${webdevetc_url()} `);

The url is https://webdevetc.com/
webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about What are Template literals (Template strings) in JS?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the JavaScript language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to replace values in a string, in JS

How to reverse htmlentities() / What is the opposite of htmlentities()?

How to set custom HTTP headers in Apache (by editing .htaccess)

What is Agile software development?

How to manually write your own pagination in PHP

Force trailing slash (redirect if no trailing slash exists) in .htaccess

How to make Apache force download of files (in .htaccess)

How to make multiple routes share the same URL structure or URL parameters

How to output (echo/print) content in PHP

What are generators in PHP, and how do they compare to arrays?