JavaScript Array keys()

Posted by

Method

Introduction to the JavaScript Array keys() Method

The Array.keys() method is used to return an array containing the keys of all elements in an array. It is part of the JavaScript array prototype, which means that it is available for all arrays, and can be used to iterate over the elements or properties of an array.

Syntax and Usage of the JavaScript Array keys() Method

The syntax for the Array.keys() method is as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let arrayKeys = array.keys();

[/dm_code_snippet]

Here, ‘array’ is the array for which the keys are to be returned. The ‘arrayKeys’ variable is used to store the returned array of keys.

Example Usage of the JavaScript Array keys() Method

Let’s look at a simple example of the Array.keys() method. Consider the following array of names:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let names = ["John", "Mary", "Adam", "Sophia"];

[/dm_code_snippet]

We can use the Array.keys() method to get all the keys of the elements in this array:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let keys = names.keys(); 

[/dm_code_snippet]

This will return an array of keys, which in this case would be [0,1,2,3]. This can be used to iterate over the elements in the array.

Conclusion

In this tutorial, we discussed the JavaScript Array keys() method. We saw its syntax and usage, as well as an example of how to use it. The Array.keys() method is a useful built-in array method, which can be used to iterate over the elements of an array.