Maizere Pathak.Nepal
Maizere Pathak.Nepal

Reputation: 2411

Why do the document.write() and alert() methds render JavaScript objects differently?

What is the difference between document.write() method and window.alert() when printing arrays and objects?

The different behaviors are shown in this code sample:

var arr = new Array("Maizere","Pathak");

document.write(arr); // output: Maizere,Pathak
alert(arr); // output: maizere,pathak

Why are they both printing the values? Shouldn't alert() print Object Object?

With a DOM object, it prints [object HTML collection] and here it is printing values.

Upvotes: 1

Views: 3206

Answers (4)

Andreas Louv
Andreas Louv

Reputation: 47099

To extend Jonathan Sampson's answer and to give a little mind crusher...

var names = ['Jonathan', 'Sampson'];
names.toString = function () {return 0;};
names.valueOf = function () {return 1;};

console.log(names + ""); // 1 or 0 ? What do you think.
console.log(names.toString()); // 1 or 0 ? What do you think.¨
alert( names );

See demo

Upvotes: 1

Sampson
Sampson

Reputation: 268344

Objects in JavaScript have a toString method. This method is called whenever the object is used in a way that text is expected. For instance, the following outputs [object Object]:

alert({});

Arrays have their own version of the toString method that does something altogether different. Rather than showing their type, they show their contents, joined by commas. You can replace an arrays toString method if you like:

var names = ['Jonathan', 'Sampson'];

names.toString = function () {
    return this.length;
};

alert(names); // Outputs 2

You can use something else's toString implementation too if you like:

document.toString.call(names); // [object Array]

For additional information, see toString on MSDN.

Upvotes: 2

Guffa
Guffa

Reputation: 700362

Both the document.write and window.alert methods use a string, so the Array.toString method will be used to produce a string value from the array.

What the toString method produces from different types of objects may vary between browsers, but you will get the same result from document.write and window.alert as they use the same method to produce the string.

Upvotes: 1

legacybass
legacybass

Reputation: 592

Both alert and document.write are setup to work with the .toString() method. For instances of type object, this usually prints [object Object]. However, the Array class has overloaded this method to print the contents of the array. Try doing arr.toString() to show this is the case. If you create an object and give it a toString method, it will be called for alert. For example:

var obj = {};
obj.toString = function() { return "I'm an Object!"; }
alert(obj);

will show an alert with the string "I'm an Object!" in it.

Upvotes: 1

Related Questions