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);
user1342369
  • 1,041
  • 2
  • 9
  • 9

3 Answers3

14

This will probably do what you're looking for:

console.dir(window);
David Gorsline
  • 4,933
  • 12
  • 31
  • 36
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.

Tronix117
  • 1,985
  • 14
  • 19
  • 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 Apr 19 '12 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.

borchvm
  • 3,533
  • 16
  • 44
  • 45
Matt
  • 41,216
  • 30
  • 109
  • 147