-3

Following are code with output

var myArray = ["one", "two","three", "four"];
var arr = [myArray];
console.log(arr);               //ouput - [Array[4]]
window.document.write(arr);     //ouput - one,two,three,four

Why both line gives different output? Thanks in advance.

Sunil Madan
  • 457
  • 1
  • 4
  • 17

2 Answers2

3

console.log will know the structure of Array or Object or any javascript data. So it print it properly.

console.log(myArray) //  ["one", "two", "three", "four"]

While, document.write will call toString() method on it(arr).So it print one,two,three,four

window.document.write(arr.toString() // one,two,three,four
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
0

document.write() calls the toString() on the array.

You can use array.toString() for the same result

Piyush.kapoor
  • 6,715
  • 1
  • 21
  • 21