-2

In instances when a javascript function returns an object, what is a good way of determining what exactly it is that you got?

If I do this:

alert(myFunction(this));

And I get back simply [object Object], what are some useful things that I can do to determine what it is?

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
KWallace
  • 1,570
  • 1
  • 15
  • 25

3 Answers3

2

if debugging don't use alert, use the console instead

console.log(myFunction(this));
console.dir(myFunction(this));
console.error(myFunction(this));
//etc

If you are trying to determine the type of object and do something depending on what it is use typeof or instanceof

Using typeof

var something = myFunction(this);
if(typeof something === "string"){
   console.log("It's a string");
}

Using instanceof

var something = myFunction(this);
if(something instanceof HTMLElement){
    console.log("It's an html element");
}
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
1

Use console.log method to display data in your console instead of alert :

console.log(myFunction(this));

In some browsers you can use console.dir, so you can get more details about the object :

console.dir(myFunction(this));

Example

var myObj = {foo: 'bar'}

alert(myObj);

console.log(myObj); //Check your console, you can see the object
console.dir(myObj); //You can see the object with more details

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

Example: http://jsfiddle.net/6daL71zd/

You can use:

1)

console.log(myFunction(this))

to print out to the console

(this can be accessed via your browser's developer tools...the 'F12' key on your keyboard should open it)

2)

var output = document.createTextNode(JSON.stringify(myFunction(this)));
document.body.appendChild(output);

to print out on the page.

Alvin Pascoe
  • 1,189
  • 7
  • 5