DEV Community

Megan Paffrath
Megan Paffrath

Posted on

1

JavaScript: String Template Literals

String template literals give us a cleaner way to concatenate our strings and variables.

Let's say we have 5 hens and 3 roosters.

let hens = 5;
let roosters = 3;
Enter fullscreen mode Exit fullscreen mode

We want to print out "We have 8 chickens, 5 of which are hens and 3 of which are roosters."

We could say:

let str = "We have " + (hens+roosters) + " chickens, " + hens + " of which are hens and " + roosters + " of which are roosters.";

// str = 'We have 8 chickens, 5 of which are hens and 3 of which are roosters.'
Enter fullscreen mode Exit fullscreen mode

Or we could say

let str = `We have ${hens + roosters} chickens, ${hens} of which are hens and ${roosters} of which are roosters.`

// str =  'We have 8 chickens, 5 of which are hens and 3 of which are roosters.'
Enter fullscreen mode Exit fullscreen mode

The second way of making this string is easier to both code and read!

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up