Array.prototype.valueOf() does not return a comma-separated copy of the array's elements. It returns the array object itself. If an old example prints comma-separated text, that text appears because the array is converted to a string afterward.
const scripts = ["PHP", "ASP", "JavaScript", "HTML"];
const result = scripts.valueOf();
console.log(result === scripts); // true
console.log(result); // the same array
const values = [1, 2, 3];
const result = values.valueOf();
console.log(result === values); // true
result.push(4);
console.log(values); // [1, 2, 3, 4]
Because result is the same array object, mutating one reference changes what the other reference observes.
The original page used document.write(scripts.valueOf()) and saw comma-separated values. The important correction is that valueOf() returned the array, and then the writing/string-conversion step converted that array to text.
const scripts = ["PHP", "ASP", "JavaScript", "HTML"];
const sameArray = scripts.valueOf();
console.log(String(sameArray)); // PHP,ASP,JavaScript,HTML
console.log(sameArray === scripts); // true
For explicit text conversion, use toString() or join().
const data = ["PHP", ["Apache", "IIS"]];
const result = data.valueOf();
console.log(result === data); // true
console.log(String(result)); // PHP,Apache,IIS
Again, the comma-separated output comes from string conversion, not from valueOf() itself.
In ordinary application code, you rarely need to call array valueOf() directly because the default method simply returns the object itself. It is more useful as part of understanding JavaScript's object-to-primitive conversion process than as an array-display method.
| Goal | Use |
|---|---|
| Get the same array object | array.valueOf() (usually unnecessary) |
| Comma-separated text | array.toString() |
| Custom separator | array.join(separator) |
| Preserve JSON-compatible structure | JSON.stringify(array) |
| Copy the top-level array | [...array], Array.from(array), or array.slice() |
valueOf() returns all array elements as primitive values. It returns the array object.valueOf() to copy an array. The returned value is the same object.valueOf() instead of the later string conversion.Empty an Array Display Array Elements
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.