Javatpoint Logo
Javatpoint Logo

JavaScript Array keys() Method

The keys() method creates and returns a new iterator object which holds the key for every index in the array. This method does not affect the original array.

Syntax

Parameter

It does not hold any parameter.

Return

It returns a new array iterator object.

JavaScript Array keys() Example

Let's see some examples to understand better.

Example1

Here's the simple implementation of keys() method in array.

Test it Now

Output:

JavaScript Array keys() Method

So, according to the number of elements present in the array, a key is assigned to each one.

Example2

Implementing keys() method with holes in between the array.

Test it Now

Output:

JavaScript Array keys() Method

Note: It is clear from the above example that Array keys() method does not ignore the holes present as an array element in the given array. It assigns a key value to that empty hole too. Also, the keys are assigned in an increasing order sequence to each element.

Example3

Test it Now

Output:

JavaScript Array keys() Method

Example4

Here's an example to generate keys for a user-define array.

Test it Now

Output:

Initially, the user will input the elements through prompt box which will be displayed as:

JavaScript Array keys() Method

After clicking on Get Keys button, the keys will be generated as:

JavaScript Array keys() Method

Thus, keys() method is a direct approach forgenerating keys for the array values.


Next TopicJavaScript Array





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA