Susantha7
Susantha7

Reputation: 936

objects convert using js toString() method gives Odd result?

code in the below shown results of few conversions of data types using toString() method. all other data types can convert to strings using toString() method but when try to convert object to string using toString() method it gives odd result it is "[object Object]"

var b =1
b.toString();// produce "1"


var x=function(){var y=1;};
x.toString();// produce "function (){var y=1;}"


var z = [1,2];
z.toString();// produce "1,2"

var a = new Date;
//a = Date {Thu Dec 25 2014 22:44:32 GMT+0530 (Sri Lanka Standard Time)}
a.toString();// produce "Thu Dec 25 2014 22:44:32 GMT+0530 (Sri Lanka Standard Time)"



var obj = { name: 'John' }
obj.toString();// produce "[object Object]"

i wanna know when we try to convert object to string using toString() method why it gives a odd result .

instead of giving "[object Object]" why wont toString() method returns this value "{ name: 'John' }"

Upvotes: 0

Views: 692

Answers (2)

Sampath Liyanage
Sampath Liyanage

Reputation: 4896

Javascript has several built-in Objects,

Eg:

  • JavaScript Number Object
  • JavaScript Boolean Object
  • JavaScript String Object
  • JavaScript Array Object
  • JavaScript Date Object
  • JavaScript Math Object
  • JavaScript RegExp Object

Each Object has the toString method implemented in different ways.


For user-defined objects the default toString method returns [object Object]. You can override it if you want..

function Car(type){
    this.type = type;
}

Car.prototype.toString = function(){
    return this.type + " car";
}

var car = new Car('bmw');
alert(car.toString());// produce "bmw car"

Also you can even rewrite Object.prototype.toString method (but may be not a good idea).

Object.prototype.toString = function() {
   return JSON.stringify(this);    ;
}

var obj = { name: 'John' }
alert(obj.toString());// produce "{ "name": "John"}"

Upvotes: 0

Diptendu
Diptendu

Reputation: 2158

In Javascript all objects inherit from Object. For a custom object if you don't define the toString() method it will inherit it from its parent class. So obj.toString() prints "[object Object]" because it is an object (a primitive type) of type Object.

Upvotes: 1

Related Questions