I have to find the last letter of a string. I think I have the correct answer, but I keep getting the error: "
lastLetterOfLastName should be “e”."
var lastName = “Lovelace”;
var lastLetterOfLastName = lastName[lastName.length - 7];
Can someone please tell me what I’m missing? I’ve also tried refreshing the screen and resubmitting, as well as typing out everything again. Thank you!
lastName.length is 8, right?
lastName.length - 7 is 1, right?
lastName[lastName.lenght - 7] you are actually writing
That is not the last letter of
Hi ieahleen, thanks for your fast reply
Ok, so I changed it to - 1, but now I don’t understand why that worked. I thought you had to put 7, cos it’s on the 7th index, seeing as they’re counted from zero. The 8th letter should be 7.
Could you please explain why it’s 1? I obviously didn’t understand something. And thanks again!
You are right, the last letter in this case is at index 7, so you get it with
You want a way of writing it that is valid whatever is the length.
lastName.length being 8, you substract 1 from it and get 7
Every time you substract 1 from the length of an array or string you the the index of last element in the array or last character in the string
lastName === 'L'
lastName === 'o'
lastName === 'v'
and so on…
lastName.length === 8. Because there are 8 characters in the string.
To get last letter you want to subtract 1 from length.
Because length starts with 1 and indexes of a string start with 0.
lastName[lastName.length - 1] === lastName[8 - 1]
I see…so I’m subtracting from the back, not really subtracting from 8? The answer is -1 because I’m saying find the last letter by taking away 1 (for last), and not - 7, because the length may not always be 8 characters?
lastname[-1] option works, because when you give the index a negative value, it starts from the right end of the string, and goes backward.
Thanks snowmonkey! You put it really simply which helps a lot. I’m brand spanking new to coding.
lastname[-1] is not valid syntax. Never use it.
You’re doing great, the trick is to keep trying things. Sometimes they break, then we learn what not to do, and hopefully why. Then, the next bit – don’t be afraid to ask questions And don’t be afraid to ask them again, and again.
That answer needs to be unflagged. We don’t want to be teaching people the wrong thing.
Thank you so much! All encouragement is super appreciated!
You are doing a mathematical operation to get
7 inside the brackets.
lastName[lastName.length - 1]
In this case the length is 8, so that part is evaluated as
8, then you have
8 - 1 inside the brackets which is evaluated to 7
You use the
length property because in this way you don’t have to know the length of the string to being able to find the index of last letter. You know that the index of last letter is always one less than the length, so in that way you can get it letting the code find the length of the string and substracting one from it