SKU // 29

JavaScript Strings

A string is a piece of text: a name, a sentence, a password, a single letter, or even nothing at all. Formally, a string is zero or more characters written inside quotes. Strings are one of the types you will use most, because nearly everything a user sees or types is text.

// Creating Strings

You can use double quotes, single quotes, or backticks:

let a = "Volvo XC60";    // double quotes
let b = 'Volvo XC60';    // single quotes: exactly the same string
let c = `Volvo XC60`;    // backticks: a template string (next lesson)
let empty = "";          // zero characters: still a string

Single and double quotes work identically; there is no difference at all between them. Pick one style and use it consistently. Backticks have extra powers, covered in JS String Templates.

// Quotes Inside Strings

A string can contain quotes, as long as they do not match the quotes around it:

let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';
let answer4 = `He's often called "Johnny"`;   // backticks allow both

Matching quotes are a problem, because JavaScript thinks the string has ended:

let text = "We are the so-called "Vikings" from the north.";
SyntaxError: Unexpected identifier 'Vikings'

JavaScript reads "We are the so-called " as a complete string, then finds the word Vikings sitting loose in the code, which makes no sense to it. The whole script fails to run.

// Escape Characters

To put a matching quote inside a string, put a backslash \ in front of it. The backslash is the escape character: it tells JavaScript "the next character is part of the text, not code":

let text1 = "We are the so-called \"Vikings\" from the north.";
let text2 = 'It\'s alright.';
let text3 = "The character \\ is called backslash.";

console.log(text1);
console.log(text3);
We are the so-called "Vikings" from the north. The character \ is called backslash.

Notice that to get one backslash into the string, you write two. A single \ would try to escape the next character.

Code Result Use it?
\"Double quoteOften
\'Single quoteOften
\\BackslashOften (file paths)
\nNew lineOften
\tHorizontal tabSometimes
\rCarriage returnRarely
\bBackspaceRarely
\fForm feedRarely
\vVertical tabRarely

The last four were designed to control typewriters, teletypes, and fax machines. You will almost never need them, and they do nothing useful in a web page.

console.log("Line one\nLine two");
console.log("Name:\tAlex");
console.log("C:\\Users\\alex");
Line one Line two Name: Alex C:\Users\alex
Watch out: \n in a web page
\n makes a new line in the console and in text boxes. But when you put a string into a web page's HTML, HTML ignores line breaks, and the text all runs together on one line. On a page you need an HTML <br> tag instead.

// String Length

Every string has a length property: the number of characters it holds. Spaces and punctuation count:

console.log("ABCDEFGHIJKLMNOPQRSTUVWXYZ".length);
console.log("Hi there!".length);
console.log("".length);
26 9 0

Note: length is a property, not a method, so it has no parentheses. "hi".length() is a TypeError.

// Characters by Position

Each character has a position number, called its index, starting at 0. Use square brackets to read one:

let word = "Code";
//          C=0 o=1 d=2 e=3

console.log(word[0]);
console.log(word[3]);
console.log(word[word.length - 1]);   // the last character
console.log(word[10]);                  // past the end
C e e undefined

Because the first index is 0, the last index is always length - 1. This is the same rule as arrays.

// Joining Strings

The + operator joins strings together. This is called concatenation:

let first = "Ada";
let last  = "Lovelace";
let full  = first + " " + last;
console.log(full);
Ada Lovelace

Breaking long strings

You cannot press Enter in the middle of a quoted string; that is a SyntaxError. To split a long string across lines in your code, break it into pieces and join them with + at the end of each line:

let message = "This is a very long message that would " +
              "run off the edge of the editor if it were " +
              "all on one line.";

It is still one string. Backtick strings, in the next lesson, can span lines directly.

// Strings Cannot Be Changed

Strings are immutable: once created, their characters cannot be edited in place. You make a new string instead.

let name = "cat";
name[0] = "b";          // silently ignored
console.log(name);

name = "b" + name.slice(1);   // build a new string from "b" + "at"
console.log(name);
cat bat

(slice(1) copies everything from index 1 onward; JS String Methods covers it.) Normally name[0] = "b" fails without any error. In strict mode it throws TypeError: Cannot assign to read only property '0' of string 'cat', which is much more helpful.

Note
Every string method you will meet (uppercase, trim, replace and so on) returns a new string. The original is never touched. If you want to keep the result, assign it to a variable.

// Numbers in Quotes Are Text

console.log(5 + 5);
console.log("5" + "5");
console.log(typeof "5");
10 55 string
Watch out
Values typed into a web form always arrive as strings, even if they look like numbers. Convert them before doing math, with Number() (covered in JS Number Methods).

// Strings as Objects (Don't)

Normally strings are simple primitive values: let x = "John";. But, like booleans, they can also be created as objects with new. Never do this; it slows code down and breaks comparisons:

let x = "John";
let y = new String("John");

console.log(typeof y);
console.log(x == y);      // loose: converts y, then compares
console.log(x === y);     // strict: string vs object

let a = new String("John");
let b = new String("John");
console.log(a == b);      // two objects: never equal
object true false false

That last one is the killer: two String objects holding identical text are not equal, even with ==, because comparing two objects checks whether they are the same object, not whether they hold the same text.

// Quick Check

Which of these is not a valid string?

  1. "It's here"
  2. 'It\'s here'
  3. 'It's here'
  4. `It's here`
Show answer
C. The apostrophe matches the single quotes around the string, so JavaScript thinks the string ends after It. B fixes it with an escape; A and D use different outer quotes.

What does this log?

let word = "planet";
console.log(word.length, word[1], word[word.length - 1]);
Show answer
6 l t. Six characters; index 1 is the second character (l); the last index is 5, which is t.

How do you write a string containing a single backslash, like C:\temp?

  1. "C:\temp"
  2. "C:\\temp"
  3. "C:/temp"
  4. "C:\'temp"
Show answer
B. \\ produces one backslash. A is a trap: \t is a tab, so it gives C: followed by a tab and emp.

// Try It

  1. Click Open Playground. Put your own full name in fullName and log its length, then its first and last characters
  2. Write the Vikings sentence with escaped quotes, then again using single quotes on the outside
  3. Log a three-line message using \n
  4. Log new String("hi") === new String("hi") and explain the result
// Video Walkthroughs
Last updated: Oct 9, 2026, 11:54 PM ET