Reading the length
Every string has a length property holding the number of characters in it. It is a property, not a method, so there are no parentheses after it:
let message = "Hello world";
console.log(message.length);
message += "!";
console.log(message.length);
11
12
Spaces count as characters, which is why "Hello world" has 11 and not 10. The empty string "" has length 0. After the +=, the variable refers to a new, longer string, so reading length again gives the new value.
Reaching characters from the end
Indexes start at 0, so the last character of a string is at index length - 1. The nth character from the end is at length - n:
let message = "Hello world";
let length = message.length;
console.log(message[length - 1]);
console.log(message[length - 2]);
d
l
This works for a string of any size, which is the reason to use length instead of typing the number. If the text changes later, the code still finds its last character.
Slicing from the end
The length also gives you the starting point for taking the last n characters. Start at length - n and run to the end:
let message = "Hello world";
let length = message.length;
console.log(message.slice(length - 4));
console.log(message.slice(length - 7));
orld
o world
Both slice and substring accept a start and an end index, and the end is excluded. If the end is the length of the string, the result runs to the last character, so message.substring(message.length - 5, message.length) and message.substring(message.length - 5) are equivalent.
What length really counts
The length is the number of UTF-16 code units, which is the same as the number of characters for ordinary text. Characters outside the basic range, such as many emoji, take two units:
console.log("héllo".length);
console.log("😀".length);
console.log([..."😀"].length);
5
2
1
Spreading the string into an array splits it by whole characters instead, so the third line is 1. For the plain English text in this chapter you won't see a difference.
Length in a loop
The length is also the boundary of most string loops. This one walks from the last index down to 0 and builds the text backwards:
const word = "pancakes";
let reversed = "";
for (let i = word.length - 1; i >= 0; i--) {
reversed += word[i];
}
console.log(reversed);
sekacnap
The loop starts at word.length - 1, the last valid index, and stops after index 0. For an empty string, the start is -1, so the body never runs and reversed stays empty. Reading length in the loop condition costs almost nothing, so you don't need to save it in a variable first.
Empty strings
Whitespace-only strings are not empty either: " " has length 1.
An empty string has length 0, which makes s.length === 0 the usual test for "no text". The last-character formula needs care here: s[s.length - 1] is s[-1], which is undefined, so check for an empty string first when the input might be empty.
The exercise
The starter code declares a message:
let message: string = "I love pancakes";
- Print the length:
message.length, which is 15. - Print the last character: index
message.length - 1, which is 14. - Print the last 5 characters with
substring. They start at indexmessage.length - 5and end atmessage.length, sincesubstringalso excludes its end index.
let message: string = "I love pancakes";
console.log(message.length);
console.log(message[message.length - 1]);
console.log(message.substring(message.length - 5, message.length));
The output is:
15
s
cakes
Gotchas
- Off by one.
message[message.length]isundefined, because the last valid index islength - 1. - Method syntax.
message.length()is an error, becauselengthis a number, not a function. - Short strings. If a string has fewer than 5 characters,
message.length - 5is negative. in the exercise's form with the length as the end,substringtreats the negative start as 0 and returns the whole string. For"abc"that isabc, whereasslicecounts a negative start from the end and returnsbc. - You can't assign to it. Setting
message.length = 3doesn't shorten the string, because strings are immutable.
Key takeaways
s.lengthis the number of characters, spaces included.- The last character is at
length - 1, and the nth from the end atlength - n. - The last
ncharacters start atlength - n. lengthis a property; it needs no parentheses.