0

I found out that if we do a code to get first and last arrays like this:

function firstLast(array) {
 var first = array[0];
 var last = array[array.length - 1];
return [first, last];
}

It works, I found that solution to get last array in the internet, but I can’t figure out why the - 1 would give the last instead of the first index since the array itself is counting 0, 1, 2, 3... from the lowest to highest. So why is that? The ++ would not work for that? Can someone give me explanation and/or examples please?

4
  • 3
    Since the indexes are 0 based, the last index is alway 1 less than the length of the array. Commented Nov 24, 2019 at 15:12
  • 2
    Have you tried seeing what array.length - 1 is? Commented Nov 24, 2019 at 15:13
  • the index you're using is not -1, it's array.length - 1 instead; which should indeed give you the last index Commented Nov 24, 2019 at 15:13
  • If you have 5 elements in the array the indexes are 0,1,2,3,4. Now array.length will return 5, so you need to substract 1 to get 4. Commented Nov 24, 2019 at 15:38

2 Answers 2

2

Here's an example that you can try in the console:

var places = ['first', 'second', 'third']
=> undefined

places[0]
=> "first"

places.length
=> 3

places.indexOf('third')
=> 2

places.length-1
=> 2

places[places.length-1]
=> "third"
Sign up to request clarification or add additional context in comments.

Comments

0

Thanks guys, seems so easy now that it’s explained. But i couldn’t think about that.. all arrays starts as 0 so - 1 in length shall give the last index value, that would not work in php with index starting as 1 right? Thanks everyone

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.