Strings
What you'll learn:
- get a character of a string by its index and find out the string's length;
- build a string from text and values with a template literal;
- cut out, search for and transform parts of a string with methods;
- explain why
"10" < "9", and compare words alphabetically.
![A plate cat of three cells numbered 0 1 2, an empty dotted cell after it, the first cell tagged word[0]](/course-covers/javascript-beginners/07-strings.webp)
Picture a sign where every letter is printed in its own cell. The cells are numbered from left to right, and the count starts at zero. That is how JavaScript stores text.
A string is a sequence of characters, and each character has a number. You can get a character by its number, and JavaScript knows the length of the string on its own. Let's look at the word "cat":
const word = "cat";
console.log(word.length); // 3
console.log(word[0], word[2]); // c t
console.log(word[3]); // undefined
console.log(word[word.length - 1]); // t
console.log(word[0] + word[1]); // caLet's go through the output line by line:
word.lengthis the length of the string:"cat"has three characters.word[0]andword[2]are the first and the last cells,candt.word[3]: there is no cell number3, so the expression givesundefined.word[word.length - 1]is the last character again: its number is one less than the length.word[0] + word[1]glues two characters into the stringca.
Length and indexes
A property is a value read through a dot after a name. You have already met one: Math.PI. Every string has the length property: the number of characters in it. The empty string "" has length 0.
The number of a character is called its index, like the number of an array element. Indexes count from 0, so the last character is word[word.length - 1].
What else to know about indexes:
- a character taken by index is a string too, of length
1; - an index past the end of the string causes no error: the expression
word[3]givesundefined; - in a string of length
n, indexes run from0ton - 1.
That is why a loop goes through the characters in turn: the counter i runs from 0 while i < word.length. A for…of loop over the string gives the same order.
A Latin or Cyrillic letter, a digit and a space each count as one character: "кот".length is 3 too. Most emoji count as two characters or more. So a string with an emoji can be longer than it looks.
A string cannot change
Back to the sign. Its text is printed: you cannot rub out one letter and write in another. But you can print a new sign and hang it in place of the old one.
Strings work the same way. Strings are immutable: the characters of a created string never change. An assignment by index does nothing. What you can change is the variable: put a new string into it. The + operator does not touch its strings either; it creates a third one from them.
Strings have methods — functions called through a dot on a value: pet.toUpperCase(). A string method does not change the string; it returns a new one. Let's check all of this on an example:
let pet = "cat";
pet[0] = "b";
console.log(pet); // cat
const loud = pet.toUpperCase();
console.log(loud, pet); // CAT cat
pet = "b" + pet[1] + pet[2];
console.log(pet); // batlet pet = "cat"puts the string"cat"into the variable.pet[0] = "b"tries to replace the first letter, but the string does not change, and the program printscat.pet.toUpperCase()returns a new string"CAT", andloudstores it.petitself is stillcat.pet = "b" + pet[1] + pet[2]builds a new string"bat"and puts it into the variable. This is the new sign in place of the old one.
Here the analogy ends: nobody has to take down the old sign and throw it away. When no one needs a string any more, JavaScript frees its memory on its own.
The assignment pet[0] = "b" is silently skipped only in a plain script. In strict mode, with "use strict" at the top of the file, the same assignment stops the program. This is the Node.js and Chrome text:
TypeError: Cannot assign to read only property '0' of string 'cat'Interviewers like to ask this: "Can you change a character of a string?" The answer has two parts:
- no, strings are immutable, and methods and
+create a new string; - a write by index is silently skipped, and in strict mode it stops the program with a
TypeError.
Common mistake
A method is called, but its result is not stored anywhere:
const user = "ann";
user.toUpperCase(); // ✗
console.log(user); // annThere is no error, but the string user stays the same. The method returned a new string "ANN", and it was lost because nobody stored it. Store the result in a variable: const upper = user.toUpperCase(); — then upper equals "ANN".
Key points
- A string is a sequence of characters with indexes from
0tolength - 1. s[i]gives a character — a string of length1— and an index past the end givesundefined.- Strings are immutable: methods and
+return a new string instead of changing the old one. - Store a method's result in a variable, or it is lost.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.