Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

What is array keys() in JavaScript?

Samia Ishaque

Overview

The keys function in Javascript creates an object of the type array iterator, which holds the keys of the array. The general syntax for the keys function is as follows:

array.keys()

Parameters

The keys function takes no mandatory input as an argument.

Return value

The keys function returns an array iterator object, which can be used to iterate the keys of an array.

Example

The example below will help you understand the keys function in more depth. First, we include the working days of a week in an array and call the keys function on the array to create an array iterator object. Once we have an array iterator, we can use it to iterate over the array’s keys by using a for loop and printing each key to the console. In this example, we print each index and its value.

const array_days = ["Monday", "Tuesday", "Wednesday", "Thursday","Friday"];
const iterator = array_days.keys();

for (let x of iterator) {
  console.log(`iterator value ${x} corresponds to ${array_days[x]}`);
}

RELATED TAGS

javascript

CONTRIBUTOR

Samia Ishaque
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring