|
| 1 | +--- |
| 2 | +Title: '.keys()' |
| 3 | +Description: 'Returns a new array iterator object containing the keys for each index in the array.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Web Development' |
| 7 | +Tags: |
| 8 | + - 'Arrays' |
| 9 | + - 'Iterators' |
| 10 | + - 'JavaScript' |
| 11 | + - 'Methods' |
| 12 | +CatalogContent: |
| 13 | + - 'introduction-to-javascript' |
| 14 | + - 'paths/front-end-engineer-career-path' |
| 15 | +--- |
| 16 | + |
| 17 | +The **`.keys()`** method returns a new array iterator object containing the keys (indices) for each index in the array. |
| 18 | + |
| 19 | +## Syntax |
| 20 | + |
| 21 | +```pseudo |
| 22 | +array.keys(); |
| 23 | +``` |
| 24 | + |
| 25 | +**Parameters:** |
| 26 | + |
| 27 | +- This method does not take any parameters. |
| 28 | + |
| 29 | +**Return value:** |
| 30 | + |
| 31 | +- A new array iterator object containing the keys (indices) of the array. |
| 32 | + |
| 33 | +## Example 1: Using `.keys()` to Get Array Indices |
| 34 | + |
| 35 | +In this example, the `.keys()` method creates an iterator over the indices of the array: |
| 36 | + |
| 37 | +```js |
| 38 | +const cats = ['Sundae', 'Gandalf', 'Campanita']; |
| 39 | +const catsIterator = cats.keys(); |
| 40 | + |
| 41 | +for (const cat of catsIterator) { |
| 42 | + console.log(cat); |
| 43 | +} |
| 44 | +``` |
| 45 | + |
| 46 | +Here is the output: |
| 47 | + |
| 48 | +```shell |
| 49 | +0 |
| 50 | +1 |
| 51 | +2 |
| 52 | +``` |
| 53 | + |
| 54 | +## Example 2: Converting the `.keys()` Iterator to an Array |
| 55 | + |
| 56 | +In this example, the spread operator (`...`) with `.keys()` is used to convert the index iterator into a full array of indices: |
| 57 | + |
| 58 | +```js |
| 59 | +const colors = ['red', 'black', 'white']; |
| 60 | +const indices = [...colors.keys()]; |
| 61 | + |
| 62 | +console.log('Array indices: ', indices); |
| 63 | +console.log('First index: ', indices[0]); |
| 64 | +``` |
| 65 | + |
| 66 | +Here is the output: |
| 67 | + |
| 68 | +```shell |
| 69 | +Array indices: [0, 1, 2] |
| 70 | +First index: 0 |
| 71 | +``` |
| 72 | + |
| 73 | +## Codebyte Example: Using `.keys()` with Sparse Arrays |
| 74 | + |
| 75 | +In this codebyte example, `.keys()` is used on a sparse array. Even though some elements are missing, `.keys()` still returns all valid indices: |
| 76 | + |
| 77 | +```codebyte/javascript |
| 78 | +const sparseArray = ['Lia', , 'ny', , '💖']; |
| 79 | +const keys = [...sparseArray.keys()]; |
| 80 | +
|
| 81 | +console.log('Keys:', keys); |
| 82 | +console.log('Length:', sparseArray.length); |
| 83 | +``` |
0 commit comments