5

I want to do a function that can be used a lot in debugging that print all variables with their values. It would alert:
x=3
y=2

The function would be like that :
Exemple :

var text='';
for(var a=0;a<allVariables;a++)
{
    text+=nameOfVariable + " = " + valueOfVariable + "/n";
}
alert(text);
4
  • Use console.log for debugging.
    – malletjo
    Commented Apr 19, 2012 at 17:11
  • In addition to console.log, I highly recommend using the dev tools available for browsers. Chrome has one built-in (F12), and FireFox has FireBug extension/plugin
    – Matt
    Commented Apr 19, 2012 at 17:12
  • @racar You probably want to find out what browser op is using before you suggest that. Also, why NOT use alert if that's what you prefer?
    – Madbreaks
    Commented Apr 19, 2012 at 17:28
  • Possible duplicate of Getting All Variables In Scope Commented May 31, 2016 at 9:57

3 Answers 3

16

This will probably do what you're looking for:

console.dir(window);
1

You should use console methods, it's the best for debugging. Quite all modern browsers have the console, and you can use better debugging tools like firebug for firefox. Then a simple console.log(allVariables) and it is all shown in the console.

1
  • 1
    You mean, all variables of the page ? They are all stored in the window object in webbrowsers and in the global object in node.js. So you just have to do console.log(window) to see all declared variables. Otherwise you can declare allVariables: allVariables={x:3, y:2}; console.log(allVariables);
    – Tronix117
    Commented Apr 19, 2012 at 17:18
1

It can be difficult to determine what "all the variables" are if you use anything global. By default, global variables all fall under the window scope. So you could loop over all values in window, but that would give you everything else as well.

If you put everything inside of a namespace, you can be more explicit about it.

var MyVariables = {
};

MyVariables.foo = 1;
MyVariables.hello = 'world';

for(var name in MyVariables){
    console.log(name, MyVariables[name]);
}

Also check out the dev tools available on your browser. I personally would recommend Chrome Dev tools (builtin, F12), or FireBug in FireFox. IE does have some built-ins as well.

2
  • how do i access to that window scope (i could do a regex to have the variables only) Commented Apr 19, 2012 at 17:49
  • @user1342369 it's just window. e.g. window.foo
    – Matt
    Commented Apr 19, 2012 at 17:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.