Episode 2: Template Literals | Template Strings in Modern JavaScript Development | Salesforce ☁️⚡️


 Template literals or Template Strings are delimited with backtick(`) characters, template literals allows you to perform some actions mostly create a string by doing substitution of placeholders which can be little complicated if you will use the normal way.

Let’s understand it by few examples:


Example 1: Use Template Literals with parameters


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const myUser={
  firstName:"Kapil",
  lastName:"Batra"
  }

  //Following 'User' is not available
  //Standard way 
  console.log('Following \'User\' is not available: '+myUser.firstName);

  //Modern way 
  console.log(`Following 'User' is not available: ${myUser.firstName}`);


Output



Example 2: Use it with Multi-line String

Using backtick sign you can simply give the next line by just pressing the enter key in a string. No need of \n anymore :)


1
2
3
4
5
6
7
//Standard Way using \n
console.log('Line 1\nLine 2\nLine 3');

//Modern Way using enter key
console.log(`Line 1
Line 2
Line 3`);


Output



Example 3: String Interpolation (Concatenate String with Parameters)


1
2
3
4
5
6
//Standard Way
const a = 5;
const b = 10;
console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + ".");
// "Fifteen is 15 and
// not 20."


1
2
3
4
5
6
7
//Modern Way
const a = 5;
const b = 10;
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20."


Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals


Checkout Complete Video Tutorial Below

 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Happy Coding :)

Post a Comment

0 Comments