Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the JavaScript equivalent of var_dump or print_r in PHP? [duplicate]

I would like to see the structure of object in JavaScript (for debugging). Is there anything similar to var_dump in PHP?

like image 267
Adriana Avatar asked Mar 02 '09 21:03

Adriana


People also ask

Is there a Var_dump in JavaScript?

The var_dump equivalent in JavaScript? Simply, there isn't one. Prints an interactive listing of all properties of the object. This looks identical to the view that you would see in the DOM tab.

What is Var_dump function in PHP?

The function var_dump() displays structured information (type and value) about one or more expressions/variables. Arrays and objects are explored recursively with values indented to show structure. All public, private and protected properties of objects will be returned in the output.

What is the difference between Var_dump () and Print_r ()?

var_dump() displays values along with data types as output. print_r() displays only value as output. It does not have any return type. It will return a value that is in string format.

What is Var_dump in PHP w3schools?

The var_dump() function dumps information about one or more variables. The information holds type and value of the variable(s).


2 Answers

Most modern browsers have a console in their developer tools, useful for this sort of debugging.

console.log(myvar); 

Then you will get a nicely mapped out interface of the object/whatever in the console.

Check out the console documentation for more details.

like image 54
Paolo Bergantino Avatar answered Oct 01 '22 18:10

Paolo Bergantino


Most common way:

console.log(object); 

However I must mention JSON.stringify which is useful to dump variables in non-browser scripts:

console.log( JSON.stringify(object) ); 

The JSON.stringify function also supports built-in prettification as pointed out by Simon Zyx.

Example:

var obj = {x: 1, y: 2, z: 3};  console.log( JSON.stringify(obj, null, 2) ); // spacing level = 2 

The above snippet will print:

{   "x": 1,   "y": 2,   "z": 3 } 

On caniuse.com you can view the browsers that support natively the JSON.stringify function: http://caniuse.com/json

You can also use the Douglas Crockford library to add JSON.stringify support on old browsers: https://github.com/douglascrockford/JSON-js

Docs for JSON.stringify: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

I hope this helps :-)

like image 44
Francesco Casula Avatar answered Oct 01 '22 17:10

Francesco Casula