CodeBlanks Logo Icon CodeBlanks

Creating strings

JavaScript course · Beginner · Lesson 30/133

Learn to create strings with single and double quotes and the difference between them.

What is a string?

In JavaScript text is stored as a string. A string is zero or more characters wrapped in single quotes (') or double quotes (").

Examples: 'hello', "hello", "42", ''. Single and double quotes are equivalent; which one you pick is a style choice.

When the text itself contains quotes, picking the other kind on the outside saves trouble: "Ayşe's book" or 'He said "great"'. A string always returns "string" when you ask typeof.

Nested quotes

If you want to use the same kind of quote inside a string, you must mark the inner quote with a backslash: 'Ayşe\'s' or "He \"said\" that".

The easier path is to use a different quote on the outside. Writing "Ayşe's book" reads better than 'Ayşe\'s book'.

The same rule applies the other way: 'He said "great"' works without any escape.

Exercise Declare two strings and log them

Declare name with single quotes as 'Alex'. Declare city with double quotes as "Berlin". Then log both with console.log.

Show example solution
const name = 'Alex';
const city = "Berlin";
console.log(name);
console.log(city);

Test yourself

  1. Which one is a valid string literal?

    • merhaba
    • 'merhaba'
    • (merhaba)
    • {merhaba}
    Show answer

    'merhaba' — Correct. 'merhaba' wrapped in quotes is a string literal.

  2. Define a string with single quotes

    const city = ____;
    Show answer
    const city = 'Berlin';
  3. Match each expression to its meaning

    'str'
    Single quoted string
    "str"
    Double quoted string
    str
    No quotes (variable)
    ''
    Empty string
  4. What does console.log(typeof 'merhaba'); print?

    console.log(typeof 'merhaba');
    • "string"
    • "text"
    • "hello"
    • "char"
    Show answer

    "string" — Correct. typeof always returns "string" for a string.

All lessons in Beginner