JavaScript Array .keys()
method
The array keys()
method is JavaScript is somewhat related to .entries()
method, the difference is that now we only have the keys of the reference array.
So, when .keys() is used in an array then assigned to a variable, it will create an Array Iterator
that contains the keys of the reference array which comes from their indexes.
Array .keys()
Method Syntax
This is how you can use the the .keys()
method.
const fruits = ["🍉", "🍌", "🍍"];
const fruitKeys = fruits.keys();
for (const fruit of fruitKeys) {
console.log(fruit);
}
// the output would be:
// 0
// 1
// 2
Just like .entries()
method, the .keys() method it does not alter or change the original array.
To access the values inside the array iterator
, we can use the for loop
method just like the example above, or using the .next()
method that's avaible on Array Iterators in JavaSCript. So, continuing with our fruits
array as an example above, let's access each array item using the .next()
method.
const fruits = ["🍉", "🍌", "🍍"];
const fruitKeys = fruits.keys();
console.log(fruitKeys.next().value);
console.log(fruitKeys.next().value);
console.log(fruitKeys.next().value);
console.log(fruitKeys.next().value);
// 0
// 1
// 2
// undefined
Watch: Array .keys()
Method Tutorial
Check out this tutorial video for more details about .keys()
method in JavaScript.