Timmah
Timmah

Reputation: 1335

Automatically console.log the name and value of all variables in a script

I often find one of the most repetitive tasks when writing JavaScript is the need to constantly check the value of variables, especially as a script grows more complex.

Is there a way to automatically log the variable values to the console via calling a function?

e.g.

var foo = 1,
    bar = true,
    yin = ['item 1', 'item 2'],
    yang = 'a string',
    tan = $(this);

function() {
    yang = 'another string';
}

foo += 1;

yin.push('item 3');

function logMyVariables();

would log:

foo: 2
bar: true
yin: item1, item2, item 3
yang: another string
tan: [object Object]

Upvotes: 2

Views: 1972

Answers (1)

Julien Grégoire
Julien Grégoire

Reputation: 17134

You can call debugger;. This will pause your script and give you a snapshot at that point of many things, including all variables, local and global.

Try to run the snippet below with your dev tools opened, you'll see the result. This works in Chrome and Firefox at least.

function init() {
  var foo = 1,
    bar = true,
    yin = ['item 1', 'item 2'],
    yang = 'a string',
    tan = this;

  (function(){
    yang = 'another string';
    
  }());

  foo += 1;

  yin.push('item 3');

  debugger;

}

init();

Upvotes: 1

Related Questions