Strings are made of characters. The string "cat" is made of the characters "c", "a", and "t".
We can access the individual characters in a string by putting square brackets after the string that contain a character index.
Take a look at this example:
console.log("cat"[1]);
Indexes start at 0
We might expect the above code to give us "c" as a result, since we passed 1
as the index and "c" is the first character.
However, "a" was the result. Why? Because computers start counting at 0.
Any time we are working with an index (the computer's way of numbering something), the first item will be at position 0.
Try this:
console.log("cat"[0]);
The output of the above code is "c" instead.
The end of the string
We know the beginning of a string is at position 0. What about the end of a string?
Using the length
property, we can determine the index at the end of the string.
Look at this function:
function getLastCharacter(string) {
return string[string.length - 1];
}
console.log(getLastCharacter("cat"));
The first character is at index 0, which is the number we normally use (1) minus 1.
The last character is also at the number we normally use minus one.
If a string is 4 characters long, we normally number them 1-4. Computers number them 0-3.
To get the index of the last character, start with the string's length and subtract 1.