JavaScript Array valueOf()

Posted by

Method

JavaScript Array valueOf() Method

The JavaScript Array valueOf() method is used to return the primitive value of an array. This method returns a shallow copy of the array and does not modify the original array. It returns the same type as that of the array elements.

Syntax

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

array.valueOf()

[/dm_code_snippet]

Parameter Values

The array.valueOf() method does not accept any parameters.

Return Value

Returns the primitive value of the array.

Example

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

var arr = [1, true, 'hello'];

console.log(arr.valueOf());

// Output:
// [1, true, "hello"]

[/dm_code_snippet]

Browser Support

The array.valueOf() method is supported in all major browsers, including Internet Explorer 6+, Firefox, Chrome, Opera and Safari.

More Examples

The following example demonstrates the effect of the valueOf() method on a multi-dimensional array:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

var arr = [[1,2], [3,4]];

console.log(arr.valueOf());

// Output:
// [[1,2], [3,4]]

[/dm_code_snippet]

In the following example, the valueOf() method is used to retrieve the primitive value of an array with objects:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

var obj1 = {name: 'John', age: 30};
var obj2 = {name: 'Mary', age: 40};

var arr = [obj1, obj2];

console.log(arr.valueOf());

// Output:
// [{name: "John", age: 30}, {name: "Mary", age: 40}]

[/dm_code_snippet]

Conclusion

In conclusion, the JavaScript Array valueOf() method is used to return the primitive value of an array. It returns a shallow copy of the array and does not modify the original array. It returns the same type as that of the array elements.