JavaScript Array.valueOf() Method

Shubham Vora Jan 30, 2023
  1. Syntax of JavaScript array.valueOf():
  2. Example Code: Use the array.valueOf() Method to Convert an Array Object Into an Array
  3. Example Code: Use the array.valueOf() Method to Display the Array Object as HTML Text
JavaScript Array.valueOf() Method

The array.valueOf() method returns the elements of an array object. When an array contains the elements of another array, the array.valueOf() method will flatten the contents.

Syntax of JavaScript array.valueOf():

array.valueOf();

Parameter

This method does not take any parameters.

Return

This method returns the primitive value of an array after converting an array object.

Example Code: Use the array.valueOf() Method to Convert an Array Object Into an Array

In JavaScript, we can use the array.valueOf() method to get the actual elements of an array object. In this example, we created an array and an array object.

Using the new Array() constructor, we have added arr1 to the array object. To get the primitive value of the array object, we used the array.valueOf() method.

let arr1 = ["JavaScript","Array","Object"];
let arrObj = new Array(arr1);
let refValue = arrObj.valueOf();
console.log(arrObj);

Output:

[ [ 'JavaScript', 'Array', 'Object' ] ]

Example Code: Use the array.valueOf() Method to Display the Array Object as HTML Text

We can’t use the array object to display text with JavaScript code. However, using array.valueOf() method, we can display the elements of the array object as HTML text.

In this example, we created an array object. We will use the array.valueOf() method to make an array object displayed as HTML text.

<html>
    <body>
        <div id="output"> </div>
        <script>
            let output = document.getElementById("output");
            let array = new Array("File","Document");
            let arr = array.valueOf();
            console.log(arr);
            output.innerHTML = arr;
        </script>
    </body>
</html>

Output:

File,Document

The array.valueOf() method is supported in most browsers. Using this method, we can display the elements of an array object as HTML text.

Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub

Related Article - JavaScript Array