Exercise: Basic JavaScript: Use Bracket Notation to Find the Last Character in a String
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”."
Setup:
var lastName = “Lovelace”;
My answer:
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?
So lastName.length - 7 is 1, right?
So with lastName[lastName.lenght - 7] you are actually writing lastName[1]
That is not the last letter of lastName
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 lastName[7]
You want a way of writing it that is valid whatever is the length.
So, with 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
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?
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.
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