Skip to content

Instantly share code, notes, and snippets.

@faisalman
Last active September 13, 2021 02:57
Show Gist options
  • Save faisalman/879208 to your computer and use it in GitHub Desktop.
Save faisalman/879208 to your computer and use it in GitHub Desktop.
PHP-like print_r() & var_dump() equivalent for JavaScript
Usage example
==============
-- Consider there is an object:
var obj = { foo: 'foo', bar: { foo: true, bar: null, baz: function(){alert('Hello');}}, qux: [1, 3, 2, 'qwerty', 55], quxx: /^[0-9]/ };
-- Then print_r(obj) or var_dump(obj) will return:
Object
{
foo => 'foo',
bar => Object
{
foo => true,
bar => null,
baz => function (){alert('Hello');}
},
qux => Array
[
0 => 1,
1 => 3,
2 => 2,
3 => 'qwerty',
4 => 55
],
quxx => /^[0-9]/
}
/**
* PHP-like print_r() & var_dump() equivalent for JavaScript Object
*
* @author Faisalman <movedpixel@gmail.com>
* @license http://www.opensource.org/licenses/mit-license.php
* @link http://gist.github.com/879208
* @require type.of()
*/
var print_r = function(obj,t){
var isArray = type.of(obj)==='array';
var tab = t || '';
var dump = isArray ? 'Array\n'+tab+'[\n' : 'Object\n'+tab+'{\n';
for(var i in obj){
if (obj.hasOwnProperty(i)) {
var param = obj[i];
var val = '';
var paramType = type.of(param);
switch(paramType){
case 'array':
case 'object':
val = print_r(param,tab+'\t');
break;
case 'boolean':
val = param ? 'true' : 'false';
break;
case 'string':
val = '\''+param+'\'';
break;
default:
val = param;
}
dump += tab+'\t'+i+' => '+val+',\n';
}
}
dump = dump.substring(0, dump.length-2)+'\n'+tab;
return isArray ? dump+']' : dump+'}';
};
var var_dump = print_r;
/**
* type.of() – a more specific typeof()
* by Rolando Garza
*
* http://rolandog.com/archives/2007/01/18/typeof-a-more-specific-typeof/
* http://snipplr.com/view/1996
*/
var is={
Null:function(a){
return a===null;
},
Undefined:function(a){
return a===undefined;
},
nt:function(a){
return(a===null||a===undefined);
},
Function:function(a){
return(typeof(a)==='function')?a.constructor.toString().match(/Function/)!==null:false;
},
String:function(a){
return(typeof(a)==='string')?true:(typeof(a)==='object')?a.constructor.toString().match(/string/i)!==null:false;
},
Array:function(a){
return(typeof(a)==='object')?a.constructor.toString().match(/array/i)!==null||a.length!==undefined:false;
},
Boolean:function(a){
return(typeof(a)==='boolean')?true:(typeof(a)==='object')?a.constructor.toString().match(/boolean/i)!==null:false;
},
Date:function(a){
return(typeof(a)==='date')?true:(typeof(a)==='object')?a.constructor.toString().match(/date/i)!==null:false;
},
HTML:function(a){
return(typeof(a)==='object')?a.constructor.toString().match(/html/i)!==null:false;
},
Number:function(a){
return(typeof(a)==='number')?true:(typeof(a)==='object')?a.constructor.toString().match(/Number/)!==null:false;
},
Object:function(a){
return(typeof(a)==='object')?a.constructor.toString().match(/object/i)!==null:false;
},
RegExp:function(a){
return(typeof(a)==='function')?a.constructor.toString().match(/regexp/i)!==null:false;
}
};
var type={
of:function(a){
for(var i in is){
if(is[i](a)){
return i.toLowerCase();
}
}
}
};
@faisalman
Copy link
Author

I just found out that there is a project called phpjs at http://phpjs.org , more complete set of PHP-like functions for JavaScript can be found there (including print_r() of course), however my implementation has more simple approach and doesn't need any dependencies.

@unicornist
Copy link

you could just go with JSON.stringify() instead

@ravishankarsm
Copy link

@unicornist : Superb ...Smartest of all the replies .. Thanks for that

@staimanovo
Copy link

staimanovo commented Apr 10, 2016

pure perfection :) thanks for sharing

this is the first try able to print out the "window" object (all other chokes on recursion)

@unicornist: try JSON.stringify() the "window" and see the difference

@tarreislam
Copy link

Nice ´+1

@ankurnarkhede
Copy link

ankurnarkhede commented Feb 12, 2019

You can simply use the NPM package @smartankur4u/vardump

npm install @smartankur4u/vardump --save-dev

Usage:

const vardump = require('@smartankur4u/vardump')

var variable = {
  'data': {
    'stuff': [{
      'onetype': [{
        'id': 1,
        'name': 'John Doe'
      },
        {
          'id': 2,
          'name': 'Don Joeh'
        }
      ]
    }]
  }
}


// print the variable using vardump
vardump(variable)

This will print

object(1) {
    ["data"] => object(1) {
        ["stuff"] => array(1) {
            [0] => object(1) {
                ["onetype"] => array(2) {
                    [0] => object(2) {
                        ["id"] => number(1)
                        ["name"] => string(8) "John Doe"
                    }
                    [1] => object(2) {
                        ["id"] => number(2)
                        ["name"] => string(8) "Don Joeh"
                    }
                }
            }
        }
    }
}

Thank me later!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment