Quotes in JavaScript

By

Learn the three types of quotes you can use in JavaScript: single quotes, double quotes and backticks, including multiline strings and variable interpolation.

~~~

JavaScript allows you to use 3 types of quotes to define a string:

The first 2 are essentially the same:

const animal = 'dog'
const bike = "ducati"

There’s little to no difference in using one or the other. The only difference lies in having to escape the quote character you use to delimit the string:

const test = 'test'
const test = 'te\'st'
const test = 'te"st'
const test = "te\"st"
const test = "te'st"

A practical consequence: pick the quote type based on the content. If the string contains an apostrophe, double quotes save you the escaping:

const sentence = "it's a nice day"

There are various style guides that recommend always using one style vs the other.

I personally prefer single quotes all the time, and use double quotes only in HTML. This way an HTML attribute inside a JavaScript string needs no escaping:

const link = '<a href="https://flaviocopes.com">my site</a>'

Whatever you pick, the important thing is consistency across the codebase. Tools like Prettier enforce one style automatically, so you never think about it again.

Backticks

Backticks are a recent addition to JavaScript, since they were introduced with ES6 in 2015.

They have a unique feature: they allow multiline strings.

Multiline strings are also possible using regular strings, using escape characters:

const multilineString = 'A string\non multiple lines'

Using backticks, you can avoid using an escape character:

const multilineString = `A string
on multiple lines`

Not just that. You can interpolate variables and expressions using the ${} syntax:

const multilineString = `A string
on ${1+1} lines`

Notice that interpolation only works inside backticks. Writing ${} inside single or double quotes gives you the literal characters, with no substitution. That’s a common mistake when you switch a string to interpolation and forget to change the quotes.

A pitfall with JSON

One place where the quote type is not a matter of style: JSON. The JSON format requires double quotes around strings and keys.

JSON.parse('{"name": "Roger"}') // works
JSON.parse("{'name': 'Roger'}") // throws a SyntaxError

If you hand-write JSON with single quotes, parsing fails. Keep the double quotes inside, and delimit the JavaScript string with single quotes or backticks.

I cover backticks-powered strings (called template literals) in a separate article, that dives more into the nitty-gritty details.

~~~

Related posts about js: