2

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]
6
  • What do you mean "automatically"? Like ever x number of seconds it logs? Commented May 22, 2016 at 0:03
  • @Jerry, good point, I just updated the question Commented May 22, 2016 at 0:06
  • 1
    You could store all variables in an object in the outermost scope, or make it global, and simply log that object to the console when you need to see your variables, for example: demo. Commented May 22, 2016 at 0:09
  • Are the variables you want to log global? Commented May 22, 2016 at 0:10
  • @DavidThomas, I'm after something that can traverse the script and log every variable it finds sequentially. This includes Global and Local variables, as they are encountered in the script. I don't think manually declaring them in an object would work, as this relies on already knowing their value. Commented May 22, 2016 at 0:38

1 Answer 1

1

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();

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.