jskatas.org Continuously Learn JavaScript. Your Way.

Array API: array.keys()

Array.prototype.keys() returns an iterator for all keys in the array.

Array.prototype.keys returns an iterator for all keys in the array

keys() returns an iterator
const arr = ['a', 'b']; const iterator = arr.keys(); assert.deepEqual(iterator.next(), {value: 0, done: false}); assert.deepEqual(iterator.next(), {value: void 0, done: true});
gets all keys
const arr = ['a', 'b']; const keys = Array.from(arr.keys()); assert.deepEqual(keys, [0, 1, 2]);
empty array contains no keys
const arr = ['empty me']; const keys = [...arr.keys()]; assert.equal(keys.length, 0);
a sparse array without real values has keys though
const arr = [,,]; const keys = [...arr.___()]; assert.deepEqual(keys, [0, 1]);
also includes holes in sparse arrays
const arr = ['a', , 'c']; const keys = arr.keys; assert.deepEqual(keys, [0, 1, 2]);

Required Knowledge

Related Katas

Array API

Difficulty Level


First Published

19 May 2015


5 tests to solve