Use Bracket Notation to Find the Last Character in a String

Use Bracket Notation to Find the Last Character in a String
0

#1

Here is the example given:

var firstName = "Ada";
var lastLetterOfFirstName = firstName[firstName.length - 1];

Why does the code have firsstName[firstName? Why can’t you just start with the bracket so the code would read [firstName.length - 1];

I am a little confused as why it is necessary/ what the purpose is?

Thank you!


#2

firstName is a string. When you use bracket notation with the string, you are referring to a specific index of the string.

If you just use [firstName.length -1], without preceding it with firstName, JavaScript interprets [firstName.length-1] as an array with one element and the element would be a number ( value of of firstName.length -1 ) or in the example of firstName = “Ada”, it would be an array with one element and the element would be the number 2, because firstName.length yields 3 and 3 -1 = 2.