iceWhispers
iceWhispers

Reputation: 1

Last array in JavaScript, why?

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?

Upvotes: 0

Views: 48

Answers (2)

iceWhispers
iceWhispers

Reputation: 1

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

Upvotes: 0

matthewrpacker
matthewrpacker

Reputation: 101

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"

Upvotes: 2

Related Questions