Tell us what’s happening:
I’m just confused on why you subtract one? What is the purpose… I’m lost and just trying to understand why
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;
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 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
Remember that the characters in a string are like the elements of an array. Like an array the elements start at zero. So “Ada” would be 3 characters in length, but because the index starts at zero the last character would be at position 2.
1 Like
Thanks for replying! Just double checking that I understand so…
- Ada (A=0, d=1, a = 2)
- Ada length = 3
- 3-2=1 (This is where you get the -1)
Almost. Point #3 Length, which is 3 - 1 = 2.
The last letter in string “Ada” is in position 2. [0, 1, 2]
So, when you write: firstName[firstName.length - 1];
you are really saying: firstName[3 - 1] or firstName[2] which will be ‘a’
Typically, the term string
is used to represent an array of characters… So the indices of characters in a string follow array like indices…
const string = 'Some String';`
Will be represented in memory as
['S', 'o', 'm', 'e', ' ', 'S', 't', 'r', 'i', 'n', 'g']
[ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10]
Also str.length
is 11.
Since indices start from 0 and length is 11, you last character is on 10th index. You last character’s index is always going to be 1 less that length of a string. Hence str.length - 1