JavaScript print_r() or var_dump() Equivalent
I see a lot of newer JavaScript developers asking about debugging their variables. I think what happens is that they come from a
PHP background and expect to have handy functions available like
print_r() or
var_dump().
And why not? Those are fantastic functions that are infinitely valuable. Either way, being able to debug in this manner is almost
mandatory.
Honestly, my preferred method is
Firebug's console.log(), which lets a developer
pass in a string or series of variables that it will display, like so:
I think a large majority of webdevs use both Firefox and Firebug, so this
is nothing new. But there are some edge cases in which it would be nice to have a print_r() equivalent.
For example, if you must debug in a less developer-friendly browser such as
Internet Explorer.
To satisfy these edges cases, I've put together a function similar to print_r():
This function collects the values of the passed variable and its children and returns them in a formatted string. The first parameter is the variable itself, the second is the maximum number of recursions to allow (to prevent errors), and the third is the string to use to separate or indent content (such as a space or a tab). Here are some examples:
Even if you're a devout Firebug user and this function has no use for you, I still thought it might be helpful to see how this kind of thing would be put together.
- [Download print_r.js] (1,271 bytes)
- [Download print_r-min.js] (427 bytes; compressed)
[...] JavaScript print_r() or var_dump() Equivalent var myVar = { key1 : ‘value1′, key2 : ‘value2′, key3 : ['a', 'b', 'c'] }; try { console.log(’myVar: ‘, myVar); } catch(e) { alert(”You don’t have Firebug!nFor shame…”); }. Run this example. I think a large majority of webdevs use both … [...]