/

Quotes in JavaScript: An Overview

Quotes in JavaScript: An Overview

In JavaScript, there are three types of quotes that can be used: single quotes, double quotes, and backticks. While single quotes and double quotes are essentially the same, there is a slight difference when it comes to escaping the quote character within the string. Backticks, on the other hand, were introduced with ES6 in 2015 and have a unique feature - they allow for multiline strings without the need for escape characters.

To illustrate the usage of single and double quotes, consider the following examples:

1
2
const test = 'test';
const bike = "bike";

In both cases, the quotes can be used interchangeably, but when using a quote character within the string, it needs to be escaped. Here are some examples:

1
2
3
4
5
const test = 'test';
const test = 'te\'st';
const test = 'te"st';
const test = "te\"st";
const test = "te'st";

There are style guides that recommend using one style consistently over the other. Personally, I prefer using single quotes all the time and reserve double quotes for HTML.

Backticks, also known as template literals, offer an alternative for handling multiline strings. Previously, multiline strings were possible using regular strings with escape characters, like this:

1
const multilineString = 'A string\non multiple lines';

However, using backticks, escape characters are no longer necessary:

1
2
const multilineString = `A string
on multiple lines`;

But it doesn’t stop there! Backticks also allow for variable interpolation using the ${} syntax:

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

If you want to delve deeper into the nitty-gritty details of backticks-powered strings, check out my separate article here.

tags: [“JavaScript”, “quotes”, “backticks”, “template literals”, “multiline strings”]