JavaScript - Array valueOf() Method



The JavaScript Array.valueOf() method is use to return the primitive value of an array object, which is the array itself. When we apply this method on an array, it returns the array unmodified.

For example, if we consider an array arr = [1, 2, 3]; if we use valueOf() method on this array; it returns the same array itself [1, 2, 3] as result.

Syntax

Following is the syntax of JavaScript Array valueOf() Method −

array.valueOf();

Parameters

This method does not accept any parameters.

Return value

This method for arrays returns the array itself.

Examples

Example 1

In the following example, the JavaScript Array valueOf() method is called on the array animals, and it returns the array itself.

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"];
      let result = animals.valueOf();
      document.getElementById("demo").innerHTML = result;
   </script>
</body>
</html>

Output

Lion,Cheetah,Tiger,Elephant,Dinosaur

Example 2

Here, we are calling the valueOf() method on a nested array, and it returns the same nested array itself.

<html>
<body>
   <p id="demo"></p>
   <script>
      const NestedArray = [
         [10, 20, 30],
         [40, 50, 60],
         [70, 80, 90],
      ];
      let result = NestedArray.valueOf();
      document.getElementById("demo").innerHTML = result;
   </script>
</body>
</html>

Output

10,20,30,40,50,60,70,80,90
Advertisements