JS Template Literals Tutorial – What Are Template Literals In JavaScript?

The literals delimited with backticks ( ` ) are called template literals in JavaScript. Template literals are used to embed expressions. While untagged template literals which result in strings are used for string interpolation in multiline strings.

Template literal is a very useful concept in JavaScript. We use backticks in our code and they do the trick for us. Let’s see the use of Template Literals in JavaScript in the following tutorial to understand their functions better.

const myVar = 'very'
console.log(`template literal is a very ${myVar} thing in JS`)

JS evaluates what is inside (“) on the runtime and returns the expression inside with whatever the value of the inside variable is. We can escape Template literal expressions by backslash ‘\’.

console.log(`we can add back-tick \` like this.`)

We can call functions inside template literal back-ticks. 

const aProgrammingLanguage = () => {
    return 'JavaScript'
}
console.log(`we are learning ${aProgrammingLanguage()}`)

We can also execute one line conditional statements in template literals.

const workout=true
console.log(`Harper is a ${workout?'active':'lazy'} person.`)

Another way to use template literals can be Tagged Template Literals.

function highlight(strings, name, age) {
    let string1 = strings[0]
    let string2 = strings[1]
    let string3 = strings[2]
    
    return string1+name+string2+age+string3
}

const name = 'Snickers'
const age = 100
const sentence = highlight`My dog's name is ${name} and he is ${age} years old`;
console.log(sentence)

We can also generate sentences from objects. 

const getSentence = (object) => {
    return `My name is ${object.name}, I am ${object.age} years old and I live in ${object.address}`
}

let person = {
    name: 'Harper',
    age: 34,
    address: 'ABC Street, XYZ',
}

console.log(getSentence(person))

I hope after this step-by-step template literals tutorial you have a better understanding of JS template Literals. If you have any questions please write in the comments section.