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 force SSL in Apache's .htaccess?

How to replace whitespace with a single space

How to disable file hotlinking in Apache with .htaccess

How to set the timezone to UTC in .htaccess

What are Apache MPMs?

How to destroy or remove a cookie in PHP

How to force non www in htaccess

How to order a Laravel hasMany relationship?

How to increment a value in the database

How to prevent Eloquent from adding created_at or updated_at timestamps?