-2

to get the last key of an object this is what i must write, but i don't understand why we need minus -1

Object.keys(myObject)[Object.keys(myObject).length - 1]

I have tried to remove minus 1 and it is undefined in the console.

  • 4
    Array indicies start at 0. – tkausl Aug 22 '23 at 20:47
  • 3
    `Object.keys()` is an array; in Javascript, arrays are 0-based, so the first element has index 0 and the last element has index array.length - 1. – mykaf Aug 22 '23 at 20:47
  • oh okay i forgot that, thanks everyone – user_unknown Aug 22 '23 at 20:49
  • Another way to do the same thing: `Object.keys(yourObject).at(-1)`. Although key iteration order is well-defined, normally an object is considered unordered and there is no "last key". – InSync Aug 22 '23 at 22:43

1 Answers1

-1

When searching in array, you use index. The first item in array has index 0, the next item 1, the next item 2...

However, someArray.length returns how many items are in array.

So length starts from 1 (if array isn't empty), but index starts from 0. So you need to deduct 1 :).

RedApple
  • 119
  • 3