javascript
  1. javascript-values

JavaScript values()

Syntax

The values() method is a built-in method in JavaScript that returns a new array object containing the values of each element in a given array object, in the order of their occurrence.

The syntax for values() method is:

array.values()

Example

Here is an example to illustrate the usage of values() method:

const fruits = ['apple', 'banana', 'orange'];
const fruitValues = fruits.values();

for (let fruit of fruitValues) {
  console.log(fruit); // Output: apple, banana, orange
}

Output

The above example will output:

apple
banana
orange

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fruits Example</title>
</head>
<body>

<!-- Display area for the output -->
<div id="output"></div>

<script>
    // Your JavaScript code
    const fruits = ['apple', 'banana', 'orange'];
    const fruitValues = fruits.values();

    // Display the output in the HTML document
    let outputHtml = '';
    for (let fruit of fruitValues) {
        outputHtml += `${fruit}, `;
    }

    // Remove the trailing comma
    outputHtml = outputHtml.slice(0, -2);

    document.getElementById('output').innerHTML = outputHtml;
</script>

</body>
</html>
Try Playground

Explanation

Here, we first define an array of fruits - ['apple', 'banana', 'orange']. We then use the values() method to get a new array object containing the values of each element in fruits. We store the returned array object in a variable called fruitValues.

We then use a for...of loop to iterate over each element in fruitValues and output its value to the console.

Use

The values() method can be used to extract the values of each element in an array object. It returns an array iterator object that can be used to iterate over the values in the original array.

Important Points

  • The values() method returns an iterator object, which is a new object of type Array Iterator.
  • The Array Iterator object can be used to iterate over the values of each element in the original array.
  • The values() method is part of the Array.prototype object, and therefore can be used on any array object.

Summary

The values() method in JavaScript is a built-in method that can be used to extract the values of each element in an array object. It returns an array iterator object that can be used to iterate over the values in the original array. This method is useful when you need to extract the values of all elements in an array in a specific order.

Published on: