Home > Software engineering >  When string.length - 1 is used, what exactly is being subtracted here?
When string.length - 1 is used, what exactly is being subtracted here?

Time:10-25

I took this function from code wars, this function should take the first and last letter from beast and only return if it's equal to the first and last letter of dish. But I don't undestand what "dish[dish.length - 1]" is doing.

function feast(beast, dish) {
  return beast[0] === dish[0] && beast[beast.length - 1] === dish[dish.length - 1]
}

CodePudding user response:

Strings are zero index so the length is one greater than the last position.

 Index:  012345678
Length:  123456789
String: "Hello Foo"

So the last character of a string that has a length of 9 is index position 8.

  • Related