JavaScript Debugging

From Code Self Study Wiki
Jump to: navigation, search

Notes about JS debugging.

Browser Console[edit]

See:

Methods:

  • console.log()
  • console.info('show this with an information icon')
  • console.warn('method1() is deprecated. Please use method2() instead.')
  • console.error('bug')
  • console.debug('temporary debugging message') -- blue text. Easy to grep and delete after a quick debugging session without affecting existing console.log() statements.
  • console.log('A %s, %d (number), and %o', 'string', 123, {obj: ['a', 'b', 'c']}) -- formatting for strings, numbers, and objects
  • console.count() -- can be used inside loops
console.group('Start a group');
console.log('something');
console.log('something else');
console.groupEnd();
console.groupCollapsed('Start a collapsed group');
console.log('something');
console.log('something else');
console.groupEnd();

Example from the egghead videos series:

for (var i = 0; i < 67; i++) {
    var num = Math.random() * 100;
    console.groupCollapsed('Picking random number.');
    console.log('num greater than 10?', num > 10);
    console.log('num greater than 50?', num > 50);
    console.groupCollapsed('a nested group');
    console.log(i);
    console.groupEnd();
    console.groupEnd();
}

Profiling:

console.time('countToZillions');
for (var i = 0; i < 10000000; i++) {
    1+1;
}
console.timeEnd('countToZillions');
  • console.table(someObj)
  • console.table(someObj, ['array', 'of', 'columns', 'to', 'include'])

CSS in the console:

console.log('%cCSS formatting in the console!', 'color: #fff; background-color: teal; font-size: 21px; padding: 3px; border-radius: 4px');

CSS Formatting in the Console.png