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

21

270

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

Mareld answered 27/11, 2008 at 11:29 Comment(5)
It partly depends on how you want to print it, but this is a really nice implementation that returns some HTML that you can then append to your document (or write to a debug div): james.padolsey.com/javascript/prettyprint-for-javascriptSubstratosphere
I create a JavaScript code that formats the result like PHP's var_dump: rubsphp.blogspot.com/2011/03/vardump-para-javascript.htmlFibula
I found this code snippet much better and I use this in my projects: phpjs.org/functions/var_dump:604Demo
I use the function found on this site: theredpine.wordpress.com/2011/10/23/var_dump-for-javascriptApostate
Yes, console.log( myObject ); -- assuming use in a modern browser or with debug tools if a node project. there were caveats to this at the time of asking but essentially that's it nowGama
V
225

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".

Vola answered 27/11, 2008 at 13:45 Comment(4)
I'd recommend against it as well - frankly I'd just use console.debug. But I was pointing out the possibility of looping - it is up to the user what they want to do with each propertyVickeyvicki
I've been using firebug for a while now, but wasn't aware of Firebug Lite, thanks for pointing it out.Lovable
@nickf, may i request you to have a visit at #9193490? Donnow whether such a request in comment is acceptable.Harwill
I think a slightly more robust version of this function exists at https://mcmap.net/q/98589/-what-is-the-javascript-equivalent-of-var_dump-or-print_r-in-php-duplicate which is essentially a duplicate of print_r for phpGeognosy
V
111

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
}
Vickeyvicki answered 27/11, 2008 at 11:34 Comment(2)
I love this method because I only need to type a few bytes. I use it often.Ataghan
This works when developing react-native apps as well - love it!Ethben
B
66

A lot of modern browsers support the following syntax:

JSON.stringify(myVar);
Boiney answered 12/8, 2011 at 0:18 Comment(2)
It fires an exception when receiving circular structures instead of guarding against them.Aggrade
Like the console. options, this only shows the variable's contents, it doesn't label the variable, so if you dump a bunch of variables, you have to manually label each one. :-(Broadleaved
G
28

It can't be stated enough that you can use console.debug(object) for this. This technique will save you literally hundreds of hours a year if you do this for a living :p

Gratiana answered 3/1, 2011 at 19:1 Comment(3)
That's amazing. I had never heard of console.debug(object) before today, and it saved me a ton of time on a form I've been struggling with for three days. Withing 20 minutes, I had it fixed. Thank you!Mayst
It would be better if it actually displayed the name of the variable instead of just its contents so that you can see a bunch of variables at the same time without having to manually label them all. ¬_¬Broadleaved
@Broadleaved try console.debug({object}). If you need multiple: console.debug({object1, object2}).Ascariasis
M
10

To answer the question from the context of the title of this question, here is a function that does something similar to a PHP var_dump. It only dumps one variable per call, but it indicates the data type as well as the value and it iterates through array's and objects [even if they are Arrays of Objects and vice versa]. I'm sure this can be improved on. I'm more of a PHP guy.

/**
 * Does a PHP var_dump'ish behavior.  It only dumps one variable per call.  The
 * first parameter is the variable, and the second parameter is an optional
 * name.  This can be the variable name [makes it easier to distinguish between
 * numerious calls to this function], but any string value can be passed.
 * 
 * @param mixed var_value - the variable to be dumped
 * @param string var_name - ideally the name of the variable, which will be used 
 *       to label the dump.  If this argumment is omitted, then the dump will
 *       display without a label.
 * @param boolean - annonymous third parameter. 
 *       On TRUE publishes the result to the DOM document body.
 *       On FALSE a string is returned.
 *       Default is TRUE.
 * @returns string|inserts Dom Object in the BODY element.
 */
function my_dump (var_value, var_name)
{
    // Check for a third argument and if one exists, capture it's value, else
    // default to TRUE.  When the third argument is true, this function
    // publishes the result to the document body, else, it outputs a string.
    // The third argument is intend for use by recursive calls within this
    // function, but there is no reason why it couldn't be used in other ways.
    var is_publish_to_body = typeof arguments[2] === 'undefined' ? true:arguments[2];

    // Check for a fourth argument and if one exists, add three to it and
    // use it to indent the out block by that many characters.  This argument is
    // not intended to be used by any other than the recursive call.
    var indent_by = typeof arguments[3] === 'undefined' ? 0:arguments[3]+3;

    var do_boolean = function (v)
    {
        return 'Boolean(1) '+(v?'TRUE':'FALSE');
    };

    var do_number = function(v)
    {
        var num_digits = (''+v).length;
        return 'Number('+num_digits+') '+v;
    };

    var do_string = function(v)
    {
        var num_chars = v.length;
        return 'String('+num_chars+') "'+v+'"';
    };

    var do_object = function(v)
    {
        if (v === null)
        {
            return "NULL(0)";
        }

        var out = '';
        var num_elem = 0;
        var indent = '';

        if (v instanceof Array)
        {
            num_elem = v.length;
            for (var d=0; d<indent_by; ++d)
            {
                indent += ' ';
            }
            out = "Array("+num_elem+") \n"+(indent.length === 0?'':'|'+indent+'')+"(";
            for (var i=0; i<num_elem; ++i)
            {
                out += "\n"+(indent.length === 0?'':'|'+indent)+"|   ["+i+"] = "+my_dump(v[i],'',false,indent_by);
            }
            out += "\n"+(indent.length === 0?'':'|'+indent+'')+")";
            return out;
        }
        else if (v instanceof Object)
        {
            for (var d=0; d<indent_by; ++d)
            {
                indent += ' ';
            }
            out = "Object \n"+(indent.length === 0?'':'|'+indent+'')+"(";
            for (var p in v)
            {
                out += "\n"+(indent.length === 0?'':'|'+indent)+"|   ["+p+"] = "+my_dump(v[p],'',false,indent_by);
            }
            out += "\n"+(indent.length === 0?'':'|'+indent+'')+")";
            return out;
        }
        else
        {
            return 'Unknown Object Type!';
        }
    };

    // Makes it easier, later on, to switch behaviors based on existance or
    // absence of a var_name parameter.  By converting 'undefined' to 'empty 
    // string', the length greater than zero test can be applied in all cases.
    var_name = typeof var_name === 'undefined' ? '':var_name;
    var out = '';
    var v_name = '';
    switch (typeof var_value)
    {
        case "boolean":
            v_name = var_name.length > 0 ? var_name + ' = ':''; // Turns labeling on if var_name present, else no label
            out += v_name + do_boolean(var_value);
            break;
        case "number":
            v_name = var_name.length > 0 ? var_name + ' = ':'';
            out += v_name + do_number(var_value);
            break;
        case "string":
            v_name = var_name.length > 0 ? var_name + ' = ':'';
            out += v_name + do_string(var_value);
            break;
        case "object":
            v_name = var_name.length > 0 ? var_name + ' => ':'';
            out += v_name + do_object(var_value);
            break;
        case "function":
            v_name = var_name.length > 0 ? var_name + ' = ':'';
            out += v_name + "Function";
            break;
        case "undefined":
            v_name = var_name.length > 0 ? var_name + ' = ':'';
            out += v_name + "Undefined";
            break;
        default:
            out += v_name + ' is unknown type!';
    }

    // Using indent_by to filter out recursive calls, so this only happens on the 
    // primary call [i.e. at the end of the algorithm]
    if (is_publish_to_body  &&  indent_by === 0)
    {
        var div_dump = document.getElementById('div_dump');
        if (!div_dump)
        {
            div_dump = document.createElement('div');
            div_dump.id = 'div_dump';

            var style_dump = document.getElementsByTagName("style")[0];
            if (!style_dump)
            {
                var head = document.getElementsByTagName("head")[0];
                style_dump = document.createElement("style");
                head.appendChild(style_dump);
            }
            // Thank you Tim Down [http://stackoverflow.com/users/96100/tim-down] 
            // for the following addRule function
            var addRule;
            if (typeof document.styleSheets != "undefined" && document.styleSheets) {
                addRule = function(selector, rule) {
                    var styleSheets = document.styleSheets, styleSheet;
                    if (styleSheets && styleSheets.length) {
                        styleSheet = styleSheets[styleSheets.length - 1];
                        if (styleSheet.addRule) {
                            styleSheet.addRule(selector, rule)
                        } else if (typeof styleSheet.cssText == "string") {
                            styleSheet.cssText = selector + " {" + rule + "}";
                        } else if (styleSheet.insertRule && styleSheet.cssRules) {
                            styleSheet.insertRule(selector + " {" + rule + "}", styleSheet.cssRules.length);
                        }
                    }
                };
            } else {
                addRule = function(selector, rule, el, doc) {
                    el.appendChild(doc.createTextNode(selector + " {" + rule + "}"));
                };
            }

            // Ensure the dump text will be visible under all conditions [i.e. always
            // black text against a white background].
            addRule('#div_dump', 'background-color:white', style_dump, document);
            addRule('#div_dump', 'color:black', style_dump, document);
            addRule('#div_dump', 'padding:15px', style_dump, document);

            style_dump = null;
        }

        var pre_dump = document.getElementById('pre_dump');
        if (!pre_dump)
        {
            pre_dump = document.createElement('pre');
            pre_dump.id = 'pre_dump';
            pre_dump.innerHTML = out+"\n";
            div_dump.appendChild(pre_dump);
            document.body.appendChild(div_dump);
        }  
        else
        {
            pre_dump.innerHTML += out+"\n";
        }
    }
    else
    {
        return out;
    }
}
Mendicant answered 21/9, 2014 at 19:19 Comment(0)
B
8

You want to see the entire object (all nested levels of objects and variables inside it) in JSON form. JSON stands for JavaScript Object Notation, and printing out a JSON string of your object is a good equivalent of var_dump (to get a string representation of a JavaScript object). Fortunately, JSON is very easy to use in code, and the JSON data format is also pretty human-readable.

Example:

var objectInStringFormat = JSON.stringify(someObject);
alert(objectInStringFormat);
Bobsledding answered 29/8, 2015 at 19:12 Comment(0)
P
7

console.dir (toward the bottom of the linked page) in either firebug or the google-chrome web-inspector will output an interactive listing of an object's properties.

See also this Stack-O answer

Paleoclimatology answered 1/8, 2012 at 17:20 Comment(1)
Too bad it doesn't actually label it; it only shows its value which doesn't help if you want to see a bunch of variables. :-|Broadleaved
C
6

If you use Firebug, you can use console.log to output an object and get a hyperlinked, explorable item in the console.

Conch answered 27/11, 2008 at 11:39 Comment(1)
The problem with this is that it doesn't label the variable, so if you dump a bunch of variables, you have to manually label them all to differentiate them. :-\Broadleaved
A
4

A bit of improvement on nickf's function for those that don't know the type of the variable coming in:

function dump(v) {
    switch (typeof v) {
        case "object":
            for (var i in v) {
                console.log(i+":"+v[i]);
            }
            break;
        default: //number, string, boolean, null, undefined 
            console.log(typeof v+":"+v);
            break;
    }
}
Argueta answered 13/2, 2013 at 2:31 Comment(0)
K
4

I improved nickf's answer, so it recursively loops through objects:

function var_dump(obj, element)
{
    var logMsg = objToString(obj, 0);
    if (element) // set innerHTML to logMsg
    {
        var pre = document.createElement('pre');
        pre.innerHTML = logMsg;
        element.innerHTML = '';
        element.appendChild(pre);
    }
    else // write logMsg to the console
    {
        console.log(logMsg);
    }
}

function objToString(obj, level)
{
    var out = '';
    for (var i in obj)
    {
        for (loop = level; loop > 0; loop--)
        {
            out += "    ";
        }
        if (obj[i] instanceof Object)
        {
            out += i + " (Object):\n";
            out += objToString(obj[i], level + 1);
        }
        else
        {
            out += i + ": " + obj[i] + "\n";
        }
    }
    return out;
}
Kamal answered 28/11, 2013 at 8:14 Comment(0)
T
4
console.log(OBJECT|ARRAY|STRING|...);
console.info(OBJECT|ARRAY|STRING|...);
console.debug(OBJECT|ARRAY|STRING|...);
console.warn(OBJECT|ARRAY|STRING|...);
console.assert(Condition, 'Message if false');

These Should work correctly On Google Chrome and Mozilla Firefox (if you are running with old version of firefox, so you have to install Firebug plugin)
On Internet Explorer 8 or higher you must do as follow:

  • Launch "Developer Tools, by clicking on F12 Button
  • On the Tab List, click on "Script" Tab"
  • Click on "Console" Button in the right side

For more informations you can visit this URL: https://developer.chrome.com/devtools/docs/console-api

Tales answered 20/10, 2014 at 10:45 Comment(0)
H
4

You can simply use the NPM package var_dump

npm install var_dump --save-dev

Usage:

const var_dump = require('var_dump')

var variable = {
  'data': {
    'users': {
      'id': 12,
      'friends': [{
        'id': 1,
        'name': 'John Doe'
      }]
    }
  }
}

// print the variable using var_dump
var_dump(variable)

This will print:

object(1) {
    ["data"] => object(1) {
        ["users"] => object(2) {
            ["id"] => number(12)
            ["friends"] => array(1) {
                [0] => object(2) {
                    ["id"] => number(1)
                    ["name"] => string(8) "John Doe"
                }
            }
        }
    }
}

Link: https://www.npmjs.com/package/@smartankur4u/vardump

Thank me later!

Halla answered 5/3, 2019 at 7:50 Comment(0)
D
3

If you are looking for PHP function converted in JS, there is this little site: http://phpjs.org. On there you can get most of the PHP function reliably written in JS. for var_dump try: http://phpjs.org/functions/var_dump/ (make sure to check the top comment, this depends on "echo", which can also be downloaded from the same site)

Darnelldarner answered 19/10, 2014 at 5:50 Comment(0)
T
2

I used the first answer, but I felt was missing a recursion in it.

The result was this:

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

    var pre = document.createElement('pre');
    pre.innerHTML = out;
    document.body.appendChild(pre);
}
Trumpery answered 3/2, 2015 at 18:32 Comment(0)
B
2

Based on previous functions found in this post. Added recursive mode and indentation.

function dump(v, s) {
  s = s || 1;
  var t = '';
  switch (typeof v) {
    case "object":
      t += "\n";
      for (var i in v) {
        t += Array(s).join(" ")+i+": ";
        t += dump(v[i], s+3);
      }
      break;
    default: //number, string, boolean, null, undefined 
      t += v+" ("+typeof v+")\n";
      break;
  }
  return t;
}

Example

var a = {
  b: 1,
  c: {
    d:1,
    e:2,
    d:3,
    c: {
      d:1,
      e:2,
      d:3
    }
  }
};

var d = dump(a);
console.log(d);
document.getElementById("#dump").innerHTML = "<pre>" + d + "</pre>";

Result

b: 1 (number)
c: 
   d: 3 (number)
   e: 2 (number)
   c: 
      d: 3 (number)
      e: 2 (number)
Bac answered 4/8, 2015 at 15:28 Comment(1)
This is good, but it would be better if it showed the variable's name (like in PHP), so that you can differentiate multiple variables without having to manually label them.Broadleaved
S
2

Here is my solution. It replicates the behavior of var_dump well, and allows for nested objects/arrays. Note that it does not support multiple arguments.

function var_dump(variable) {
  let out = "";
  
  let type = typeof variable;
  if(type == "object") {
    var realType;
    var length;
    if(variable instanceof Array) {
      realType = "array";
      length = variable.length;
    } else {
      realType = "object";
      length = Object.keys(variable).length;
    }
    out = `${realType}(${length}) {`;
      for (const [key, value] of Object.entries(variable)) {
    out += `\n [${key}]=>\n ${var_dump(value).replace(/\n/g, "\n  ")}\n`;
  }
  out += "}";
  } else if(type == "string") {
    out = `${type}(${type.length}) "${variable}"`;
  } else {
    out = `${type}(${variable.toString()})`;
  }
  return out;
}
console.log(var_dump(1.5));
console.log(var_dump("Hello!"));
console.log(var_dump([]));
console.log(var_dump([1,2,3,[1,2]]));

console.log(var_dump({"a":"b"}));
Sheepshanks answered 6/9, 2020 at 17:31 Comment(0)
S
1

You can also use console.table(tab); It will display the full content of your array in the browser console in an elegant way.

Stricture answered 1/9, 2023 at 9:53 Comment(0)
I
0

The following is my favorite var_dump/print_r equivalent in Javascript to PHPs var_dump.

function dump(arr,level) {
    var dumped_text = "";
    if(!level) level = 0;
    
    //The padding given at the beginning of the line.
    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";
    
    if(typeof(arr) == 'object') { //Array/Hashes/Objects 
        for(var item in arr) {
        var value = arr[item];
            if(typeof(value) == 'object') { //If it is an array,
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += dump(value,level+1);
            } else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else { //Stings/Chars/Numbers etc.
        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }
    return dumped_text;
}
Isosteric answered 9/1, 2017 at 2:45 Comment(0)
P
0

Late to the game, but here's a really handy function that is super simple to use, allows you to pass as many arguments as you like, of any type, and will display the object contents in the browser console window as though you called console.log from JavaScript - but from PHP

Note, you can use tags as well by passing 'TAG-YourTag' and it will be applied until another tag is read, for example, 'TAG-YourNextTag'

/*
*   Brief:          Print to console.log() from PHP
*   Description:    Print as many strings,arrays, objects, and other data types to console.log from PHP.
*                   To use, just call consoleLog($data1, $data2, ... $dataN) and each dataI will be sent to console.log - note that
*                   you can pass as many data as you want an this will still work.
*
*                   This is very powerful as it shows the entire contents of objects and arrays that can be read inside of the browser console log.
*                   
*                   A tag can be set by passing a string that has the prefix TAG- as one of the arguments. Everytime a string with the TAG- prefix is
*                   detected, the tag is updated. This allows you to pass a tag that is applied to all data until it reaches another tag, which can then
*                   be applied to all data after it.
*
*                   Example:
*                   consoleLog('TAG-FirstTag',$data,$data2,'TAG-SecTag,$data3); 
*                   Result:
*                       FirstTag '...data...'
*                       FirstTag '...data2...'
*                       SecTag   '...data3...' 
*/
function consoleLog(){
    if(func_num_args() == 0){
        return;
    }

    $tag = '';
    for ($i = 0; $i < func_num_args(); $i++) {
        $arg = func_get_arg($i);
        if(!empty($arg)){       
            if(is_string($arg)&& strtolower(substr($arg,0,4)) === 'tag-'){
                $tag = substr($arg,4);
            }else{      
                $arg = json_encode($arg, JSON_HEX_TAG | JSON_HEX_AMP );
                echo "<script>console.log('".$tag." ".$arg."');</script>";
            }       
        }
    }
}

NOTE: func_num_args() and func_num_args() are php functions for reading a dynamic number of input args, and allow this function to have infinitely many console.log requests from one function call

Polyadelphous answered 26/7, 2018 at 12:43 Comment(0)
G
0

I just want to add something relatively important about console.log

If you are debugging large variables (like large audio or video data buffers). When you print console.log(big_variable) the console will only display a small part of it. (it seems a bit obvious).

If however, the variable is in a loop and this variable is constantly changing, if you ever "copy it into your clipboard" , what the browser will do is to ask for the variable AGAIN (and that may have changed by the time you are copying).

I'll tell you my story. I am programming an app that deals with big chunks of audio data, with Float32arrays of size 8192. If the buffer had certain characteristics, I would print the variable using console.log() and then grab that variable to test and toy around and play with it (and even use it for mocks so I can do automated testing)

However, the results would never hold. The mic would capture the audio data, store it on a this.audioBuffer variable and the whole thing would work, but when I copied that exact variable from console.log so I could us it as a mock to run some automated tests, the behaviour would change dramatically.

It took me a while to figure this out, Apparently, whenever i "copied" or "set the variable as global" in the debugger, rather than copying the variables displayed in console.log, the jsvm would ask for the this.audioBuffer again. and since the variable was being used inside of a loop, the microphone would still record and I would get a completely different sound array than what I was listening to and thought the audio buffer was in the first place.

If you are dealing with large complex data structures like audio or video files, image files... and these are subject to change when you are reading the values in the chrome /firefox / edge console, make sure you don't console.log(variable), but rather console.log(JSON.stringify(variable)). it will save you a ton of time

Geelong answered 30/11, 2021 at 12:23 Comment(0)
D
0

you can use this for strings and objects/array

function print_r(obj){
   return JSON.stringify(obj, null, "\t"); 
}
Discontinuance answered 8/12, 2022 at 16:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.