String Literals in JavaScript / TypeScript
In JavaScript, there are 3 ways to write string literals.
Single Quotes ''
With single quotes ''
:
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 \
:
console.log('I\'m loving JavaScript!')
Double Quotes ""
You get exactly the same with double quotes ""
:
console.log('Hello world!')
If you want to have a single quote inside the string, there's no need to escape it:
console.log('I\'m loving JavaScript!')
However, if you want double quotes, you need to escape them:
console.log('And that\'s when he said: "I\'m loving JavaScript"')
Backticks or Backquotes ` `
You can also create string literals with backticks (`
):
console.log(`Hello world!`)
So there's no need to escape either '
or "
:
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:
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:
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.