This content originally appeared on DEV Community and was authored by Megan Paffrath
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;
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.'
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.'
The second way of making this string is easier to both code and read!
This content originally appeared on DEV Community and was authored by Megan Paffrath

Megan Paffrath | Sciencx (2024-08-03T04:34:36+00:00) JavaScript: String Template Literals. Retrieved from https://www.scien.cx/2024/08/03/javascript-string-template-literals/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.