Introduced in ES2015 edition of the ECMAScript specification (ES6) Template Literals(or the old name for template literals: Template strings) offer a new way of making strings in JavaScript that add a lot of powerful new capabilities, such as using placeholders to embed expressions in a string and generating multiline strings more easily.
The syntax is straightforward, just use _backticks _instead of double or single quotes:
const literal = `hello!`
They provide several features that regular strings built with quotes do not, in particular:
Let’s see some useful examples.
In JavaScript, you can write a string using single quotes (‘ ‘):
const single = 'Hello'
Or using double quotes (“ “):
const double = "Hello"
There is no significant difference in JavaScript between single- or double-quoted strings.
Now, if you want to include an expression you can do:
let name= "Kesk";
const hello = "Hello" + name + "!";
console.log(hello);
//Hello Kesk
But it gets complicated if you want to format a text or you have multiples expressions inside it:
To achieve this:
//Hello Kesk!
//.This is a multiline message
//that maintains the format
We can do:
const name = "Kesk"
const s1 = "Hello " + name + "! \n"
+ ".This is a multiline message \n"
+ "that maintains the format \n";
console.log(s1);
Result in chrome dev tools.
#javascript-tips #web-development #javascript #programming