alert() return different from console.log()?

16,175

Solution 1

Since alert could be shown to users, it tends to be literal-minded (just using toString) so a developer has a lot of control over what's shown to the user. Unlike alert, console is designed for developers, and thus tends to try to interpret a call so as to provide information that a developer would find useful: e.g. "[2, 3, 4]" is a lot more useful to a developer than "[object Object]". Alert should be the same in every browser; console's behavior could vary from browser to browser (including not being supported at all, as in IE).

Solution 2

alert() converts the object passed to it into a string using the object's toString() method. Unlike alert(), console.log() is not limited to displaying a simple string and can allow you to interact with the object passed to it, for example letting you inspect its properties.

Solution 3

try alert(JSON.stringify(yourObject)); (if your browser have json.stringify....)

Share:
16,175
orolo
Author by

orolo

wait. . . what?

Updated on June 04, 2022

Comments

  • orolo
    orolo almost 2 years

    Should I be using alert() for debugging; or is there a time to use alert() vs. console.log()?

    I see that alert() and console.log() can return different results. I assumed that they were similar functions but just returned in different places.

    Back story: my boss likes to see alerts() during development but I can't get the object details in the alert (at least not easily).

    But when I run the same request through console.log, I get the object and all of it's parameters.

  • David Mulder
    David Mulder almost 12 years
    Not true, alert will give different results in different browsers, as the toString value of various objects is not the same for different browsers.