Is there an equivalent for var_dump (PHP) in Javascript?

03/26/2020 11:00:02

We need to see what methods/fields an object has in Javascript.

Verified Answer (220 Votes)

11/27/2008 18:45:38

As the others said, you can use Firebug, and that will sort you out no worries on Firefox. Chrome & Safari both have a built-in developer console which has an almost identical interface to Firebug's console, so your code should be portable across those browsers. For other browsers, there's Firebug Lite.

If Firebug isn't an option for you, then try this simple script:

function dump(obj) {
    var out = '';
    for (var i in obj) {
        out += i + ": " + obj[i] + "\n";
    }

    alert(out);

    // or, if you wanted to avoid alerts...

    var pre = document.createElement('pre');
    pre.innerHTML = out;
    document.body.appendChild(pre)
}

I'd recommend against alerting each individual property: some objects have a LOT of properties and you'll be there all day clicking "OK", "OK", "OK", "O... dammit that was the property I was looking for".

220

Answer #2 (108 Votes)

11/27/2008 16:34:16

If you are using firefox then the firebug plug-in console is an excellent way of examining objects

console.debug(myObject);

Alternatively you can loop through the properties (including methods) like this:

for (property in object) {
    // do what you want with property, object[property].value
}
108

Answer #3 (57 Votes)

08/12/2011 05:18:34

A lot of modern browsers support the following syntax:

JSON.stringify(myVar);
57
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.