JavaScript Array keys() method

The keys() method in JavaScript is used to return a new Array Iterator object that contains the keys for each index in the array. This method is typically used in conjunction with the for...of loop to iterate over the elements of an array.

Here is an example of how the keys() method works:

const array1 = ['apple', 'banana', 'orange'];

const iterator = array1.keys();

for (const key of iterator) {
  console.log(`The key is ${key}.`);
}

// the output will be:
// The key is 0.
// The key is 1.
// The key is 2.

In the code example above, we first declare an array called array1 that contains three strings: apple, banana, and orange. We then use the keys() method to create a new Array Iterator object that contains the keys for each index in the array. We then use a for...of loop to iterate over the keys of the iterator object, and for each iteration, we log a message to the console that includes the current key.

As you can see, the keys() method allows us to easily iterate over the elements of an array and access the key of each element. This can be useful when we need to perform operations on each element in an array, and we want to keep track of the key of each element.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: