Skip to main content

Command Palette

Search for a command to run...

Template Literals in JavaScript

Published
3 min read
Template Literals in JavaScript

When working with strings in JavaScript, many times we need to combine text with variables.

For example showing a user’s name, building messages or printing values.

Before template literals, we used string concatenation.

But that can get messy very quickly.

Let’s see why.


Problem with Traditional String Concatenation

Suppose we want to print a message like this:

const name = "Bruce"
const age = 35

const message = "My name is " + name + " and I am " + age + " years old"

console.log(message)

Output:

My name is Bruce and I am 35 years old

This works, but notice:

  • lots of +

  • harder to read

  • messy when string becomes longer

Now imagine doing this in bigger strings. It becomes difficult to manage.


Template Literal Syntax

To solve this problem, JavaScript introduced template literals.

Instead of using quotes (" or '), we use backticks (`).

Example:

const name = "Bruce"
const age = 35

const message = `My name is \({name} and I am \){age} years old`

console.log(message)

Much cleaner and easier to read.


Embedding Variables

Inside template literals, we can directly insert variables using:

${variable}

Example:

const hero = "Batman"

console.log(`I am ${hero}`)

Output:

I am Batman

No need for + anymore.


Multi line Strings

Another big advantage is multi line strings.

With normal strings:

const text = "Hello\nWorld"

With template literals:

const text = `Hello
World`

console.log(text)

Output:

Hello
World

No need for \n, it works naturally.


Before vs After

Before (concatenation):

const name = "Clark"

const msg = "Hello " + name + ", welcome to Metropolis"

After (template literal):

const name = "Clark"

const msg = `Hello ${name}, welcome to Metropolis`

Cleaner and easier to understand.


Visual Idea

Diagram idea: Before vs After

"Hello " + name + "!"   →   `Hello ${name}!`

Use Cases in Modern JavaScript

Template literals are used everywhere in modern JavaScript.

For example:

Dynamic messages

const score = 95

console.log(`Your score is ${score}`)

Building HTML (frontend)

const name = "Diana"

const html = `<h1>Hello ${name}</h1>`

Logging values

const item = "Laptop"
const price = 50000

console.log(`Item: \({item}, Price: \){price}`)

Why Template Literals Are Better

  • More readable

  • Less messy

  • Easy to write multi line strings

  • No need for + everywhere


Template literals make working with strings much simpler.

Instead of joining strings manually, we can directly embed values inside them.