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)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay