Day 9 - console methods

A list of a few not-so-known console methods to be used during debugging.

Open the console to see the results.

1. console.log() - The evergreen

Just to print simple messages. You can style the messages or also add variables to check their content.

      // Normal
      const array = [1, 2, 3, 4];
      console.log('String');
      console.log('String', array);

      // Interpolated
      const country = 'Antartica';
      console.log('I\'m from %s. And you?', country);

      // Styled
      const style = 'font-size: 30px; background-color: black; color: white;'
      console.log('%cStyle console log', style);
    

2. Inform, warn or show errors

      console.info('Thank you for visiting this page.');
      console.warn('Don\'t paste here any script coming from people you don\'t know');
      console.error('Something went wrong, try to reload the page.');
    

3. Run assertions

Check if variables have expected values.

      const expectedTitle = 'Console methods.';
      const actualTitle = document.querySelector('title').text;
      console.assert(actualTitle === expectedTitle, `The page title is not correct. Expected: "${expectedTitle}" - Actual: "${actualTitle}"`)
    

4. Clear the console

For when your console gets stuffed with messages and you need to clean it up.

      console.clear();
    

5. List DOM objects' properties

Can be used with other types of variables too, but the differences with console.log are not that many. That's why this method is particularly useful when you need to see all the possible methods you can call on a specific DOM Element.

      const paragraph = document.querySelector('p');
      console.log(paragraph);
      console.dir(paragraph);
    

6. What time is it?

Track how long something takes with console.time() and console

      // how long does it take to populate an array with 100,000,000 elements?
      let array = [];
      const MAX_ARRAY_LENGTH = 100000000;
      console.time('Populate array');
      for (let i = 0; i < MAX_ARRAY_LENGTH, i++) {
        array.push(i);
      }
      console.timeEnd('Populate array');
    

7. Never lose count again!

For when you console.log the same thing over and over again and need to count them all.

      // How many Fizz from 1 to 46125? How many Buzz? How many FizzBuzz?
      const countTo = 46125;
      for (let i = 1; i <= countTo; i++) {
        if (i % 3 === 0 && i % 5 === 0) {
          console.count('FizzBuzz');
        } else if (i % 3 === 0) {
          console.count('Fizz');
        } else if (i % 5 === 0) {
          console.count('Buzz');
        }
      }
    

8. Useful console methods for arrays of objects

With console.groupCollapsed() you can group together a bunch of console.log that all belong to the same group. With console.table you can show the whole content of an array of objects in a neat and clean table.

    const cities = [
    { name: 'Jakarta', nation: 'Indonesian', language: 'Indonesian', continent: 'Asia'},
    { name: 'Tokyo', nation: 'Japan', language: 'Japanese', continent: 'Asia'},
    { name: 'Rome', nation: 'Italy', language: 'Italian', continent: 'Europe'},
    { name: 'Lima', nation: 'Peru', language: 'Spanish', continent: 'South America'},
    { name: 'Maputo', nation: 'Mozambique', language: 'Portuguese', continent: 'Africa'}
    ];
    cities.forEach(city => {
      console.groupCollapsed(`${city.name}`);
      console.log(`City name: ${city.name}`);
      console.log(`City nation: ${city.nation}`);
      console.log(`City language: ${city.language}`);
      console.log(`City continent: ${city.continent}`);
      console.groupEnd(`${city.name}`);
    });
  

Bonus methods!

8. Useful console methods for arrays of objects

With console.groupCollapsed() you can group together a bunch of console.log that all belong to the same group. With console.table you can show the whole content of an array of objects in a neat and clean table.

    .trace() -> call it at a specific point in your code and see the stack trace in the logs to be able to trace how, from where and when it gets called
    
.profile() -> start it with a name console.profile('String') and finish it with console.profileEnd('String'). Eveything that happens in between is registered and profiled and can be accessed in the 'Profiles' tab in the browser.
monitor() -> check what's given to a specific function. Use case: let's say you have a function checkIfValid() that gets called every 2 seconds and you want to know values are passed into every time, while your code is running: open your console, type monitor(checkIfValid) and wait for the info to pop up on the screen.