๐ŸŽ“ A1Learner
๐Ÿ”

JavaScript Strings

A string is text inside quotes. Strings hold names, messages, and any other text a program works with.

Two quote styles

A string is text inside quotes, and either quote style works. A quote of one kind can sit inside a string of the other kind.

let first = "Ana";
let shout = "She said 'hi' today.";
console.log(first);
console.log(shout);

Counting characters

length is a property of a string. A property is a value that belongs to the string.

let word = "hello";
console.log(word.length);
console.log("".length);

Escape characters

A backslash before a quote places that quote inside the string. A backslash before the letter n adds a newline character, and length counts it as one character.

let quote = "She said \"hello\" loudly.";
console.log(quote);
let note = "First line\nSecond line";
console.log(note.length);

Example

let firstName = "Ana";
let lastName = "Lee";
let fullName = firstName + " " + lastName;
console.log(fullName);
console.log(fullName.length);

Key points

  • Single quotes and double quotes both mark a string.
  • The length property counts the characters in a string.
  • In an escape character such as \n, a backslash changes the meaning of the character after it.
  • The + operator joins two strings into one longer string.
  • A string with nothing between its quotes is an empty string, and its length is 0.

In this example, the + operator joins the first name, a space, and the last name into one string. The length property then counts 7 characters in the full name.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What is the length of the string "JavaScript"?