What is the JavaScript equivalent of var_dump or print_r in PHP?
JavaScript equivalent to PHP's var_dump
or print_r
for quick debugging is console.log()
. To inspect an object more in-depth, use console.dir()
:
For a nicely formatted JSON string in your output, use JSON.stringify()
:
In-depth Debugging with Custom and Advanced Techniques
Occasionally, a standard console.log()
doesn't shed enough light on the grand mystery that is your JavaScript object. Fear not! There are more advanced and specialised techniques in your debugging toolkit:
Debugging in Browser vs. Debugging in Node.js
Let's not forget about browser devtools, the Poirot of JavaScript debugging. But sometimes you're not in the cozy comforts of your browser environment and you need to step up your game:
Node.js util.inspect
:
Structured Clone Algorithm:
Adding Type Differentiation to Your Belt
Beyond just the values, knowing data types is half the battle. Unfortunately, JavaScript's typeof
won't make the distinction between null
and object
. But we have our ways:
Compatibility and Edge Cases
Creating a universal solution is like trying to solve a Rubik's cube blindfolded. One move might align some squares while throwing others off. Circular references, for instance, can cause JSON.stringify()
to throw errors. Luckily, there are solutions like flatted.js
or custom replacer functions designed to handle such edge cases.
Writing Humane and Performant Debuggers
Just as you wouldn't handle all criminal cases in a small-town precinct, debugging massive data shouldn't all happen in one console.log()
. Lazy-loading properties or pagination can prevent browser slowdowns and allow for organized debugging.
Reading the Manual
Lastly, debugging isn't just about pulling out tools from your kit. Sometimes, it's about learning how to use them effectively. Tools like console.log()
, console.dir()
, and JSON.stringify()
have comprehensive documentation that can offer new insights and functionality:
- console - Web APIs | MDN — Overview and usage of Console API in JavaScript.
- Util | Node.js v21.6.1 Documentation — Node.js's
util.inspect
method for object inspection. - Destructuring assignment — Understanding object destructuring in modern JavaScript.
- JSON.stringify() - JavaScript | MDN — How to convert objects to a JSON string.
- Console overview | DevTools | Chrome for Developers — Utilizing Chrome DevTools Console for debugging.
- console: table() static method - Web APIs | MDN — Displaying data efficiently with
console.table()
. - How can I get the full object in Node.js's console.log(), rather than '[Object]'? - Stack Overflow — Stack Overflow discussion on JavaScript object logging.
Was this article helpful?