template literals


(letterali modello)


Template literals = delimited with ( ` backticks )


instead of double or single quotes


allows embedded variables and expressions

let userName = "Bro"
let items = 3
let total = 75

console.log("Hello", userName)
console.log("You have", items, "items in your cart")
console.log("Your total is $", total)

result: Hello Bro
You have 3 items in your cart
Your total is $ 75

best practice using ( ` ) backticks, Template literals


let userName = "Bro"
let items = 3
let total = 75

console.log(`Hello, ${userName}`)
console.log(`You have ${items} items in your cart`)
console.log(`Your total is $: ${total}`)

result: Hello Bro
You have 3 items in your cart
Your total is $ 75

If we would like display one very long string... assign a new variable


let userName = "Bro"
let items = 3
let total = 75

let text =
`Hello, ${userName}
You have ${items} items in your cart
Your total is $: ${total}`

console.log(text)

result: Hello Bro
You have 3 items in your cart
Your total is $ 75

(updating the label)


Html

<label id="myLabel"> </label>

Javascript


let userName = "Bro"
let items = 3
let total = 75

let text = `Hello, ${userName}<br> // we can add break tag inside the backticks
You have ${items} items in your cart<br>
Your total is $: ${total}<br>`

document.getElementById("myLabel").innerHTML = text

Monitor result ⬇️