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;

We want to print out “We have 8 chickens, 5 of which are hens and 3 of which are…


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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » JavaScript: String Template Literals." Megan Paffrath | Sciencx - Saturday August 3, 2024, https://www.scien.cx/2024/08/03/javascript-string-template-literals/
HARVARD
Megan Paffrath | Sciencx Saturday August 3, 2024 » JavaScript: String Template Literals., viewed ,<https://www.scien.cx/2024/08/03/javascript-string-template-literals/>
VANCOUVER
Megan Paffrath | Sciencx - » JavaScript: String Template Literals. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/08/03/javascript-string-template-literals/
CHICAGO
" » JavaScript: String Template Literals." Megan Paffrath | Sciencx - Accessed . https://www.scien.cx/2024/08/03/javascript-string-template-literals/
IEEE
" » JavaScript: String Template Literals." Megan Paffrath | Sciencx [Online]. Available: https://www.scien.cx/2024/08/03/javascript-string-template-literals/. [Accessed: ]
rf:citation
» JavaScript: String Template Literals | Megan Paffrath | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.