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 can you check if a variable is alphanum (alphanumeric, letters and numbers only) in PHP?

What is the spaceship operator (<=>) in PHP?

What are the main error types in PHP

How to check if a string contains a certain substring?

How to find out what version of Laravel you are using?

How to use Anonymous classes in PHP 7?

How to force gzip compression in Apache with .htaccess

How to find out which php.ini file PHP is using?

How to manually write your own pagination in PHP

How do you access the php://input stream?