JavaScript ES6 — Learn Array.keys, Array.values, and Array.entries

August 17, 2017 0 Comments

JavaScript ES6 — Learn Array.keys, Array.values, and Array.entries

 

 

Array.keys()

Last week I published an article on JavaScript ES 2017: Learn Object.keys, Object.values, and Object.entries. It’s only fair to Arrays that I publish an article on their methods as well.

Disclaimer: Please note that browser support for these methods is still minimal. I’ve included links to MDN below for further reading. These three methods in general are also not nearly as useful as the Object.keys/values/entries methods either.

As a refresher, an Array is simply a list like object that we can use to store multiple values in a single variable. Here are a couple examples:

let cars = ['ford', 'chevy', 'mazda'];
let ages = [24, 53, 28];

In order to understand these three methods, you must also understand what an iterator is.

  • An iterator is an object that keeps track of its current position, while accessing items in a collection one at a time.
  • An iterator returns an object with two properties: done and value.
  • In JavaScript, an iterator provides a next() method which returns the next item in the sequence.
  • When the sequence completes, the value will equal undefined, and done will equal true.

It’s okay if this doesn’t make complete sense yet. Once we go through the below methods, everything should be clearer!

This method returns a new Array Iterator object. The object contains keys for each item in the Array, and can be advanced with next():

let arr = ['a', 'b', 'c'];
let iterator = arr.keys();
iterator.next(); // {value: 0, done: false}
iterator.next(); // {value: 1, done: false}
iterator.next(); // {value: 2, done: false}
iterator.next(); // {value: undefined, done: true}

Array.keys is not supported in Internet Explorer:

Support in browsers — via mdn

This method returns a new Array Iterator object. The object contains values for each item in the Array, and can be advanced with next():

let arr = ['a', 'b', 'c'];
let iterator = arr.values();
iterator.next().value(); // a
iterator.next().value(); // b
iterator.next().value(); // c
iterator.next().value(); // undefined

Unfortunately, Array.values doesn’t work in many browsers:

Support in browsers — via mdn

This method returns a new Array Iterator object. The object contains the entries for each item in the Array, and can be advanced with next():

let arr = ['a', 'b', 'c'];
let iterator = arr.entries();
iterator.next().value(); // [0, 'a']
iterator.next().value(); // [1, 'b']
iterator.next().value(); // [2, 'c']
iterator.next().value(); // undefined

Unfortunately, Array.entries is not fully supported in all browsers yet:

Support in browsers — via mdn


Tag cloud