Problem solving Bracket notation to find the Nth-to-Last Character in a String

Tell us what’s happening:

Dear All,
First : Happy 2020 for you all community of FreeCodeCamp :slight_smile:
may this 2020 bring you all beautiful days with nice suprises,
I have a question about this exercise of the topic:
Bracket notation to find the Nth-to-Last Character in a String.
I could solve the exercise but i don´t understand why we need to substract - 2 ?
i am counting the word Lovelace and its length is 7, it is in this moment that i don´t know
why i need to substract - 2 to get the word C ?

Could anyone please give me some orientation in this topic?

Thank you all in advance,


Your code so far

// Example
var firstName = "Ada";
var thirdToLastLetterOfFirstName = firstName[firstName.length - 3];

// Setup
var lastName = "Lovelace";

// Only change code below this line
var secondToLastLetterOfLastName = lastName[lastName.length - 2];

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36.

Challenge: Use Bracket Notation to Find the Nth-to-Last Character in a String

Link to the challenge:

1 Like

The length of Lovelace is actually 8!

Lovelace.length returns 8.

var lastName = "Lovelace";
var secondToLastLetterOfLastName = lastName[lastName.length - 2];

lastName.length = 8
lastName.length - 2 = 6
Lovelace[0] is L,
Lovelace[6] is c

It is easy to forget that length is counting each character in the string starting at 1, while array indexing is starting at 0!

1 Like

Dear @nblack4,
Thank you for your fast reply, and explanation,
just a small question in the case of the word “Lovelace”
i though i needed to begin to count with 0 ,
so would you be so kind to tell me in which cases do i need to begin to count with 0 ?
Thank you in advance,
Kind regards,

1 Like

the length is 8

but the position of the characters in the string is 0-based
so the first character is at index 0, the last character at index 7

1 Like

If you’re ever asking for the length of a string, you start at 1. If you are ever referencing something with bracket notation Lovelace[n] you start at 0. I believe this has to do with how arrays are indexed. I think when we reference a particular character in the string Lovelace, it is breaking it up into an array of chars like ['L', 'o', 'v', 'e', 'l', 'a', 'c', 'e'] and doing manipulations based off of that. I’m not positive about it but it will help to memorize length starts at 1 and when we index we start at 0.

Hope that helps!

Dear @nblack4,
Thank you for the kind explanation,
you helped me to understand this exercise,
have a wonderful day,
Kind regards,