Tell us what’s happening:
Your code so far
// Example
var firstName = "Ada";
var lastLetterOfFirstName = firstName[firstName.length - 1];
// Setup
var lastName = "Lovelace";
// Only change code below this line.
var lastLetterOfLastName = lastName[lastName.length - 7];
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-last-character-in-a-string
In your code lastName[lastName.length - 7] you are returning second character instead of last.
lastName = “Lovelace”
L o v e l a c e
1 2 3 4 5 6 7 8
To get the last character fo the lastName you need to do the following:
-
Find out what the length of the lastName is: this is done with .length property on the string
in this case, its lastName.length would give you a length of 8.
-
Next, you need to get the index of the last character which is done by doing the following
lastName.length - 1 , reason for subtracting 1 is because string index starts from 0 not 1.
So even though length returns 8 the actual position of the last element in the string is 8 -1
actual string index positions
L o v e l a c e
0 1 2 3 4 5 6 7
- Lastly, get the last character from the string by using [] oprator on the staring
lastName[lastName.length - 1] ;
which equals to following
lastName[8-1];