Lee Brindley
Lee Brindley

Reputation: 6482

JS Alert showing 'undefined'

Hi there,

I just moved from C#/C++ to JavaScript last night, and am loving it!

I've just come across some behavior that I don't understand, wondering if anyone can shed some light on it?

When I call this script, I'm getting the expected alert box showing '5.5', however after that box is closed I get another alert simply showing "undefined", can anyone shed any light on this?

Code below:

var myObj = {

age : 5,
weight : 5.5,

toString : function(){
    alert(this.weight);
}

}

alert(myObj.toString());

Many thanks

Upvotes: 1

Views: 18760

Answers (1)

nnnnnn
nnnnnn

Reputation: 150040

Your code calls alert() twice.

The first alert is the one displaying this.weight. But then the second displays whatever value is returned from the myObj.toString() function, and since you've coded that function without an explicit return value it returns undefined by default.

Normally a .toString() function would actually return a string, so you should do this:

toString : function(){
    return this.weight.toString();
}

Then you'll just get the one alert, as shown here: http://jsfiddle.net/eph7x/

And indeed then you can simply use:

alert(myObj);

...because your custom .toString() will get called automatically.

Upvotes: 8

Related Questions