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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay