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 set environmental variables in your .htaccess file

How to force SSL in Apache's .htaccess?

How to install and use jpegoptim on Linux CentOS

How to disable file hotlinking in Apache with .htaccess

How to review blog posts (written by other users) before they get published on your WordPress blog?

How to use subdomains as parameters in your routes (or in your web.php file)

How to block IPv6 IP addresses in .htaccess

How to force non www in htaccess

How to get the first row that matches some where queries, or create it if it doesn't exist (in Laravel's Eloquent)?

How to destroy or remove a cookie in PHP