AppDividend
Latest Code Tutorials

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

0

Javascript Array Values Example | Array.prototype.values() Tutorial is today’s topic. The values() method 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(). If you are not familiar with an iterator, then check out my iterators in Javascript tutorial.

Javascript Array Values Example

The syntax of Javascript Array Values is following.

array.values()

See the following example.

// app.js

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

So, the above example gives an iterator as an output.

 

Javascript Array Values Example

Now, we can get the values by 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);
}

The output is following.

 

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);

The output is following.

 

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.

Finally, Javascript Array Values Tutorial is over.

Leave A Reply

Your email address will not be published.

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