What is template literals in javascript

๐Ÿ”—What is Template Literals ?

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

Template literals key

๐Ÿ”—Template Literals

use back-ticks (``) rather than the quotes ("") to define a string

js
let text = `Learn javascript`;
console.log(text); // Learn javascript
template literals

๐Ÿ”—Quotes Inside

Strings With template literals, you can use both single and double quotes inside a string:

js
let whoiam = `Hello i'm "sumit"`;
console.log(whoiam); // Hello i'm "sumit"
string with template literals

๐Ÿ”—Multiline Strings

Template literals allows multiline strings

js
let multiline = `this is line 1
this is line 2
this is line 3`;
console.log(multiline);
Multiline Strings

๐Ÿ”—Variable substitutions

Template literals allows variables in strings

js
let fname = "sumit";
let lname = "harijan";
let fullname = `my name is ${fname} ${lname}`;
console.log(fullname); // my name is sumit harijan
Variable substitutions

๐Ÿ”—Expression substitutions

Template literals allows expressions in strings

js
let a = 5,
b = 6;
console.log(`sum of 5+6 is ${a + b}
not ${a + b + 2}`);
<GatsbyImage
image={getImage(props.multipleImages[5])}
alt="Expression substitutions"
className="first-inline-img"
/>;