DEV Community

Megan Paffrath
Megan Paffrath

Posted on

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)