Single Quotes vs. Double Quotes in JavaScript

  1. Single Quotes vs. Double Quotes in JavaScript
  2. Escape Characters Using Single Quotes in JavaScript
  3. Escape Characters Using Double Quotes in JavaScript
Single Quotes vs. Double Quotes in JavaScript

This article is about single quotes and double quotes in JavaScript source code. Let us look at the usage and advantages of these quotes in JavaScript programming.

Single Quotes vs. Double Quotes in JavaScript

To create string literals and initialize or represent the string, programmers frequently use single and double quotes in JavaScript.

'hello world' === 'hello world'  // both are same

We need to define a single standard and stick to it. We should not use one type in one JavaScript file and the other type in another.

It is important to note that whichever quoting type we used to open a string with, we need to close it with the same type.

'hello world'  // correct
'hello world'  // correct
'hello world\' // incorrec'

In JavaScript, there is no type for a single character. There is always a string to be defined by a programmer.

If there is a need to escape the specific character from a string, both quotes are used differently.

Each quote type must escape its own enclosing quote type; for example, if the string is enclosed with a single quote like 'hello world', we need to use single quotes with a backslash (/) to escape the character. And if the string is enclosed with double quotes like "hello world", then we need to use double quotes with a backslash /.

Escape Characters Using Single Quotes in JavaScript

If we used a single quote type to define a string, we would need to escape using a single quote. There is no need for double quotes to escape here.

Example:

<script>
    const website = 'We will visit \'delftstack\' website for learning.';
    const intro = 'Hello, I am a "Learner"';
    document.write(website + "<br>");
    document.write(intro)
</script>

Output:

We will visit 'delftstack' website for learning.
Hello, I am a "Learner"

Escape Characters Using Double Quotes in JavaScript

If we use a double quote type to define a string, we need to escape using the double quote. There is no need for a single quote to escape here.

Example:

<script>
    const website = "We will visit \"delftstack\" website for learning."
    const intro = "Hello, I am a 'Learner'"
    document.write(website+"<br>")
    document.write(intro)
</script>

Output:

We will visit "delftstack" website for learning.
Hello, I am a 'Learner'

Related Article - JavaScript String