0

After reading this discussion and this article, I still have this question. Let's say I have the following snippet:

var arr = new Array(3);
arr[0] = "Zero";
arr[1] = "One";
arr[2] = "Two";

document.write(arr.join(","));

If I replace the document.write() line with document.write(arr);, are they equivalent? Does the replacement statement automatically join array elements with a comma as the delimiter?

Thanks in advance!

Community
  • 1
  • 1
stanigator
  • 10,768
  • 34
  • 94
  • 129

2 Answers2

5

"But I couldn't figure out why"

This is because everything has a toString function as part of its prototype. When you write it out, this function is invoked to get the string representation of whatever it is. For arrays, the default handling is the same as join.

Array.prototype.toString.apply([1,2,3]) == Array.prototype.join.apply([1,2,3])
> true
Jamie Treworgy
  • 23,934
  • 8
  • 76
  • 119
1

Passing the array to document.write() will separate them with commas by default.

http://jsfiddle.net/XnW7V/

var arr = new Array(3);
arr[0] = "Zero";
arr[1] = "One";
arr[2] = "Two";

document.write(arr); //outputs Zero,One,Two
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • So it is separated with commas by default? – stanigator Apr 25 '12 at 20:35
  • The commas are added as part of the formatting. The array actually does not have commas in it. If you looked in memory there would be a slot for each of the elements containing the value without commas. I am guessing the document.write() function has some conditional logic within it that determines what was passed as a param, if it is an array it must join them with commas and spit out the result. – Kevin Bowersox Apr 25 '12 at 20:37
  • I meant are the commas added by default for formatting purposes according to the Javascript standard? – stanigator Apr 25 '12 at 20:38
  • I don't know if the spec states it but clearly that is the functionality of the method. – Kevin Bowersox Apr 25 '12 at 20:41