Sub topic 1
Creating Strings: Quotes, Escapes, and Primitives
A JavaScript string is a sequence of characters that represents text. Each string you write in source code is a string literal, and the value it produces is a string primitive. This chapter covers the three quoting styles, the escape sequences you can put inside them, and the basic rules that make strings primitives instead of objects. Later chapters build on this: immutability, indexing, template literals, Unicode, and wrapper objects each get their own chapter.
Prerequisites
This chapter assumes you can:
- Declare variables with
constandletand call functions. - Run JavaScript in a browser console or with Node.js (
node file.js). - Read
console.logoutput and know whattypeofreturns for basic values.
You don't need any regular expression knowledge yet.
Three Ways to Quote a String
JavaScript has three quote characters for strings:
| Syntax | Name | Multi-line without escapes | Interpolation |
|---|---|---|---|
| `'text'` | Single-quoted literal | No | No |
| `"text"` | Double-quoted literal | No | No |
| `` `text` `` | Template literal | Yes | Yes, with `${}` |
Single and double quotes behave exactly the same. Neither is faster or more correct, and the choice is a style convention, usually enforced by a formatter such as Prettier. The only practical difference is which quote character you need to escape inside the string.
const a = 'hello';
const b = "hello";
const c = `hello`;
console.log(a === b, b === c); // true true
console.log(typeof a, typeof c); // string stringAll three produce the same kind of value. A template literal with no ${} placeholders is an ordinary string once it has been evaluated. The chapter "Template Literals and Interpolation" covers placeholders and multi-line templates in detail.
Choosing a quote style
The usual rule is to pick one style for the whole codebase, then switch only when switching avoids escapes.
const s1 = "It's sunny"; // no escape needed
const s2 = 'She said "hi"'; // no escape needed
const s3 = `It's "fine"`; // both quote types, no escapes
const s4 = 'It\'s "fine"'; // works, but harder to read
console.log(s1);
console.log(s2);
console.log(s3 === s4); // trueEscape Sequences
An escape sequence is a backslash followed by one or more characters. Together they stand for a single character that would be hard or impossible to type directly. The backslash and the characters after it are not stored in the string. Only the character they represent is stored.
| Sequence | Meaning |
|---|---|
| `\n` | Line feed (newline) |
| `\r` | Carriage return |
| `\t` | Horizontal tab |
| `\\` | A single backslash |
| `\'` | Single quote |
| `\"` | Double quote |
| `` \` `` | Backtick (needed inside template literals) |
| `\0` | Null character (U+0000), only when not followed by a digit |
| `\xHH` | Character with the two-digit hex code HH, e.g. `\x41` is `A` |
| `\uHHHH` | UTF-16 code unit with the four-digit hex code, e.g. `\u00e9` is `é` |
| `\u{H...}` | Unicode code point with 1 to 6 hex digits, e.g. `\u{1F600}` |
| `\b`, `\f`, `\v` | Backspace, form feed, vertical tab |
console.log("Line 1\nLine 2");
// Line 1
// Line 2
console.log("Name:\tAda"); // Name: Ada
console.log("C:\\Users\\ada"); // C:\Users\ada
console.log("\x41\u0042\u{43}"); // ABC
console.log("caf\u00e9"); // café
console.log("\u{1F600}"); // 😀
console.log("\n".length); // 1, the escape is one character
console.log("\\".length); // 1The length checks matter. "\n" is written with two characters in your source file, but the string contains only one. This catches people out when they count characters by eye.
Unknown escapes and silent mistakes
If you put a backslash before a character that has no special meaning, JavaScript drops the backslash and keeps the character:
console.log("\d\q\k"); // dqk
console.log("C:\new\folder"); // C:
// ew\folder (wait: \n became a newline, \f a form feed)The second line is a classic bug with Windows paths. \n becomes a newline and \f becomes a form feed, and nothing throws an error. Write the backslashes as \\, or use String.raw, which keeps backslashes exactly as written (the chapter on tagged templates explains how it works):
console.log("C:\\new\\folder"); // C:\new\folder
console.log(String.raw`C:\new\folder`); // C:\new\folderEscapes that are errors
Some escapes are syntax errors, which means the script fails before any of it runs:
- Malformed hex or Unicode escapes.
"\x4","\u12", and"\u{110000}"(above the Unicode maximum of U+10FFFF) all throwSyntaxError. - Legacy octal escapes in strict mode. Code such as
"\101"(octal forA) works in sloppy scripts but is aSyntaxErrorin strict mode, which covers ES modules and class bodies."\8"and"\9"are also rejected in strict mode. Use\x41or\u0041instead. \0followed by a digit."\01"is read as a legacy octal escape, so it fails in strict mode."\0"on its own is fine.
"use strict";
console.log("\0".length); // 1
// console.log("\101"); // SyntaxError: Octal escape sequences are not allowed in strict mode.Line breaks inside quotes
A single-quoted or double-quoted literal cannot contain an unescaped line break. This is a SyntaxError:
// const bad = "first
// second";You have three alternatives:
const withEscape = "first\nsecond"; // real newline character in the value
const continued = "first \
second"; // backslash-newline: NO newline in the value
const template = `first
second`; // real newline, written literally
console.log(continued); // first second
console.log(withEscape === template); // trueThe backslash at the end of a line is a line continuation. It lets you split long source lines, but it adds nothing to the value, and any indentation on the next line does become part of the string. Most style guides prefer + concatenation or a template literal because they are clearer.
Strings Are Primitives
JavaScript has seven primitive types: string, number, bigint, boolean, undefined, symbol, and null. A primitive is a value with no properties of its own, and you compare primitives by their contents.
const x = "hello";
const y = "hel" + "lo";
console.log(typeof x); // string
console.log(x === y); // true: same characters means equalTwo arrays with the same contents are not === equal, because arrays are objects compared by reference. Two strings with the same characters always are equal. This makes strings safe to use as Map keys, as switch cases, and in equality checks.
You can still call methods on a primitive, such as "hello".toUpperCase(). When you access a property, JavaScript briefly wraps the primitive in a String object, looks the method up on String.prototype, and throws the wrapper away afterwards. You almost never need to create those wrappers yourself. The chapter "String Primitives Versus String Objects" explains why new String("x") causes trouble.
The empty string
"", '', and `` ` are all the empty string, with length 0. It is the only falsy string. Any string that contains at least one character is truthy, including " " and "0"`:
console.log(Boolean("")); // false
console.log(Boolean(" ")); // true
console.log(Boolean("0")); // true
console.log(Boolean("false")); // trueTruthiness checks such as if (input) accept a string of only spaces. If whitespace should count as empty, check input.trim() === "". Trimming is covered in a later chapter.
Common Errors at a Glance
| Symptom | Cause | Fix |
|---|---|---|
| `SyntaxError: Unexpected identifier` near a quote | Unescaped quote ends the string early | Escape it or switch quote style |
| `SyntaxError: Invalid or unexpected token` | Raw line break inside `'...'` or `"..."` | Use `\n`, `+`, or backticks |
| Path prints with gaps or missing letters | `\n`, `\t`, or `\f` in a Windows path | Double the backslashes or use `String.raw` |
| Regex built from a string doesn't match digits | `"\d"` became `"d"` | Write `"\\d"` |
| Octal escape breaks after adding `import` | Modules are strict mode | Use `\x` or `\u` escapes |
Exercise
What do these two lines log, and why do they differ? console.log("a\tb".length); console.log(String.rawa\tb.length);
Show answer
The first logs 3, because \t is one tab character between a and b. The second logs 4, because String.raw keeps the backslash and the letter t as two separate characters.
Exercise
A teammate writes const re = new RegExp("^\w+@\w+$"); to check simple email addresses, and it rejects "ada@example". Explain the bug and give two fixes.
Show answer
In a string literal, \w is not a recognized escape, so the backslash is dropped and the pattern becomes ^w+@w+$, which only matches strings made of the letter w. Fix it by escaping the backslashes, new RegExp("^\\w+@\\w+$"), or by using a regex literal, /^\w+@\w+$/.
Exercise
Write the string He said "it's done" three ways: with double quotes, with single quotes, and with a template literal, using as few escapes as possible in each.
Show answer
"He said \"it's done\"" needs two escapes. 'He said "it\'s done"' needs one. He said "it's done" needs none. All three are === equal.
Exercise
Which of these are SyntaxErrors in an ES module: "\x4G", "\u{1F600}", "\101", "\0", "\8"?
Show answer
"\x4G" is an error because \x needs two hex digits. "\101" is an error because legacy octal escapes are banned in strict mode, and ES modules are always strict. "\8" is also banned in strict mode. "\u{1F600}" and "\0" are valid.