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 check if a relation was loaded on an Eloquent model already?

Point all requests to one PHP file

What are the SPL Iterators in PHP?

How to destroy or remove a cookie in PHP

What are route patterns in Laravel?

Is multiple inheritance supported in PHP?

How to view all installed PHP modules?

What is the loop variable in a @foreach loop in Blade?

What does 'final class' and 'final function' (final method) mean in PHP?

What are the SPL data structures