Basic JavaScript: Bracket Notation finding a letter in a string- why brackets when just assigning a variable

Tell us what’s happening:
im looking at the solution here, and my first thought is… why did I have to use a bracket when assigning this variable?

var lastLetterOfLastName = lastName[lastName.length - 1]; <<<<this is the correct answer

var lastLetterOfLastName = lastName.length - 1; <<<< this is what I was considering, its wrong I know, could someone elaborate on why my train of thought was bad?

Your code so far


// Setup
var lastName = "Lovelace";

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

Your browser information:

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

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

Link to the challenge:

var lastName = "Lovelace";

Here in this example, lastName.length - 1 will return 7 because length of the string is 8 and minus 1 will yield 7.

Challenge is to print the last character of the string. So lastName.length - 1 is going to print 7 but you’re asked to print the last character so to access the last character of the string, bracket notation is used.

console.log(lastName[lastName.length - 1]); // print `e`, the last character of string.

I think this was already explained, but just to add to what was said.

Strings can be indexed into just like when getting elements in an array. So you can index into a string to get the individual characters. The index is the number you use inside the brackets.

const nums = [1,2,3];
nums[nums.length - 1];
// 3

const word = "123";
word[word.length - 1];
// "3"

When referring to the string, why use word[word.length -1] i thought you could just get the property 3 by just doing word[-1]

-1 is not a valid index.

  1. .length give you the length, i.e. the number of elements in an array, or characters in a string.

  2. When indexing you count from 0, so the last element/character will be 1 less than the length.

  3. Instead of hardcoding the index for the last element/character you use the length of the array or string (-1) so that it will work no matter what array or string you are given.

That works if the language supports that. Python supports negative index.

Edit: If language supports operator overloading then you can overload the [] operator to add custom behaviour to that operator.