How to get value at a specific index of array In JavaScript?
Just use indexer
var valueAtIndex1 = myValues[1];
Update from Chrome 92 (released on: July 2021)
You can use at
method from Array.prototype
as follows:
var valueAtIndex1 = myValues.at(1);
See more details at MDN documentation.
You can just use []
:
var valueAtIndex1 = myValues[1];
Array indexes in JavaScript start at zero for the first item, so try this:
var firstArrayItem = myValues[0]
Of course, if you actually want the second item in the array at index 1, then it's myValues[1]
.
See Accessing array elements for more info.
indexer (array[index]
) is the most frequent use. An alternative is at
array method:
const cart = ['apple', 'banana', 'pear'];
cart.at(0) // 'apple'
cart.at(2) // 'pear'
If you come from another programming language, maybe it looks more familiar.