Skip to content

String Literals in JavaScript / TypeScript

In JavaScript, there are 3 ways to write string literals.

Single Quotes ''

With single quotes '':

javascript
console.log('Hello world!')

If you want to have a single quote inside the string, you need to escape it by preceding it with a backslash \:

javascript
console.log('I\'m loving JavaScript!')

Double Quotes ""

You get exactly the same with double quotes "":

javascript
console.log('Hello world!')

If you want to have a single quote inside the string, there's no need to escape it:

javascript
console.log('I\'m loving JavaScript!')

However, if you want double quotes, you need to escape them:

javascript
console.log('And that\'s when he said: "I\'m loving JavaScript"')

Backticks or Backquotes ` `

You can also create string literals with backticks (`):

javascript
console.log(`Hello world!`)

So there's no need to escape either ' or ":

javascript
console.log(`And that's when he said: "I'm loving JavaScript"`)

Backticks ` ` Allow Multiline

Unlike string literals created with single or double quotes, string literals created with backticks are multiline:

javascript
const multilineText = `An old pond
A frog jumps in,
The sound of water.`

Backticks ` ` Allow Interpolation

Most importantly, backticks have a superpower: interpolation. You can write:

javascript
const language = 'JavaScript'
console.log(`And that's when he said: "I'm loving ${language}"`)

And ${language} will be replaced by the content of the language variable at runtime.

There is more to say about these template literals.