0

I'm wondering if there is a function or method in JavaScript such as var_dump() in PHP that prints or returns detailed information about the content of a variable, i.e. value(s) and data type. Especially in case of more complex data types like arrays and objects such a function would be very helpful...

gretarsson
  • 31
  • 1
  • 7
  • Did you research this? https://stackoverflow.com/q/323517/3001761, for example. – jonrsharpe Sep 06 '20 at 17:02
  • 1
    `console.log`…‽ – deceze Sep 06 '20 at 17:02
  • @jonrsharpe: Thanks for the link, I didn't use the term "var_dump" for searching via search engine, otherwise I probably would have found that that thread by myself. – gretarsson Sep 06 '20 at 17:13
  • @deceze: Yes, ```console.log()``` is useful but it has to be used together with other functions/methods or attribute calls that only give a single information about the content of the variable... – gretarsson Sep 06 '20 at 17:21
  • If you're using node.js, you might be looking for [`util.inspect`](https://nodejs.org/api/util.html#util_util_inspect_object_options). In general, logging an object to the console does well, and you should [learn how to use a debugger](https://developers.google.com/web/tools/chrome-devtools/) in general – Bergi Sep 06 '20 at 17:21
  • @gretarsson What do you mean by "*[`console.log`] has to be used together with other functions/methods*"? – Bergi Sep 06 '20 at 17:23
  • I don't agree with this question being closed. That other answer is specifically for objects only, and doesn't address other data types. – Nate Levin Sep 06 '20 at 17:30
  • @Bergi: For instance, in order to get the data type, you have to use ```typeof``` additionally. On the other hand, I just noted that ```console.log()``` prints the content of the variable even if its a complex data tape (which is not possible with ```echo``` in PHP or ```System.out.print()``` in Java). From that the data type becomes more or less obvious... – gretarsson Sep 06 '20 at 17:58
  • 1
    @gretarsson Try `console.log("%o", x)` to distinguish primitives (it wraps strings in quotes). But yes, the JS console does not just print text to stdout if you have attached a debugger. – Bergi Sep 06 '20 at 18:12
  • @Bergi: But ```console.log("%o", x)``` only(?) works in GoogleChrome, not in Firefox et al. However, numbers apparently can be distinguished form strings by color in the console... – gretarsson Sep 06 '20 at 22:04
  • Yes, when you are logging to `console` it depends on your environment what exactly will happen with the value - in any case it tries to output a helpful representation. If whatever is available doesn't satisfy you, you will have to write your own formatting function - there is no builtin one in JavaScript (unless you count `JSON.stringify`). – Bergi Sep 06 '20 at 22:08

0 Answers0