JavaScript array values: The Complete Guide

0
11
Javascript Array Values Tutorial

The array.values() function returns a new Array Iterator object that contains the values for each index in the array. If you are unfamiliar with an iterator, check out my iterators in JavaScript.

JavaScript array values

JavaScript array values() is a built-in method that returns the new Array Iterator object that contains the values for each index in an array. In the same way, we can retrieve the keys of the array; we can retrieve its values using Array.prototype.values().

Syntax

The syntax of Javascript Array Values is following.

array.values()

Example

See the following example.

// app.js

let NetflixShows = ['Stranger Things', 'Black Mirror',
  'You', 'The Crown', 'Dark']
                    
const it = NetflixShows.values()
console.log(it)

See the output.

Javascript Array Values Example

Now, we can get the values by a loop through that iterator.

See the following code.

// app.js

let NetflixShows = ['Stranger Things', 'Black Mirror',
  'You', 'The Crown', 'Dark']
                    
const it = NetflixShows.values()
for (const value of it) {
  console.log(value);
}

See the output.

Array.prototype.values() Tutorial

We can also print the value of the iterator using the next() method.

// app.js

let NetflixShows = ['Stranger Things', 'Black Mirror',
  'You', 'The Crown', 'Dark']
                    
const it = NetflixShows.values()
console.log(it.next().value);
console.log(it.next().value);
console.log(it.next().value);
console.log(it.next().value);
console.log(it.next().value);

See the output.

Javascript Array Values Example | Array.prototype.values() Tutorial

We can also use the for…of loop to iterate an iterator.

// app.js

let NetflixShows = ['Stranger Things', 'Black Mirror',
  'You', 'The Crown', 'Dark']
                    
const it = NetflixShows.values()
for (let value of it) {
  console.log(value)
}

Still, the output remains the same.

That’s it for this tutorial.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.