Bracket Notation to find the last character in a string

I don’t understand why this code gives a letter a not a number as a result/in the console:

var firstName = "Ada";
var lastLetter = firstName[firstName.length - 1];

I question this because this code gives me a number:

var firstName = "Ada";
console.log (firstName.length);

.length is a property for strings/arrays. It returns their “length” or how many characters/elements they consist of. firstname.length-1 would return the number of characters that firstName has minus 1, which is equal two, so firstName[2] would return the 3rd letter in firstName which is “a”(recall that strings and arrays are zero indexed, meaning you start counting from zero, so the 3rd letter is assigned with number 2).
The exercise ultimately shows how you can target the last letter in a string, by taking its length number and subtract by 1, which always gives the index of its last character.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.