Super useful console.log tricks

dhanushnehru

Dhanush N

Posted on June 13, 2024

Super useful console.log tricks

When developing, debugging or troubleshooting web applications, console.log is one of the most frequently used tools by developers. It offers a straightforward method for outputting data to the console, which helps in understanding code execution and locating problems. Still, a lot of developers are just utilising a small portion of console.log's capabilities.
We'll look at many console.log tips in this article to help you with debugging and development.

Basic Tricks:

  • Multiple Values: Log multiple values with commas separating them
console.log("Message: Hi Dhanush", 10, true);
Enter fullscreen mode Exit fullscreen mode

multiple values image

  • Template Literals: Use template literals for formatted strings:
const name = "Dhanush";
console.log(`Hello, ${name}!`);
Enter fullscreen mode Exit fullscreen mode

template literal image

Formatting and Organization:

  • console.table: Present data in a neat table format:
const data = { name: "Dhanush", hobby: "Chess" };
console.table(data);
Enter fullscreen mode Exit fullscreen mode

console table image

  • console.group/groupCollapsed: Organize logs with collapsible sections:
console.group("Network Info");
console.log("IP:", "192.168.1.1");
console.groupCollapsed("Details");  // Use for initially hidden sections
console.log("MAC Address:", "AA:BB:CC:DD:EE:FF");
console.groupEnd();
console.groupEnd();
Enter fullscreen mode Exit fullscreen mode

console group image

  • console.clear: Clear the console for a fresh start.

console clear image

Advanced Debugging:

  • console.dir: Get a detailed object structure view:
const person = { name: "Dhanush", hobbies: ["youtube", "chess"] };
console.dir(person);
Enter fullscreen mode Exit fullscreen mode

console dir image

  • console.assert: Log only if a condition fails (useful for debugging assumptions):
const age = 18;
console.assert(age >= 21, "User must be over 21");
Enter fullscreen mode Exit fullscreen mode

console assert image

  • console.count/console.countReset: Create a counter for tracking occurrences:
console.count("API Calls");  // Increments each time called
console.count("API Calls");
console.countReset("API Calls");  // Resets the counter
console.count("API Calls");
Enter fullscreen mode Exit fullscreen mode

console count image

  • console.time/console.timeEnd: Measure code execution time:
console.time("Loop Time");
for (let i = 0; i < 1000; i++) {
    // Do something
}
console.timeEnd("Loop Time");
Enter fullscreen mode Exit fullscreen mode

console time image

  • console.trace: Print a stack trace to pinpoint where an error occurred.
function a() {
  function b() {
    console.trace();
  }
  b();
}

a();
Enter fullscreen mode Exit fullscreen mode

console trace image

Browser Information and Interaction:

console.log(console): Explore the available console methods themselves.

console.log(console)
Enter fullscreen mode Exit fullscreen mode

console image

  • console.log(navigator): Access browser information (user agent, language, etc.).
console.log(navigator)
Enter fullscreen mode Exit fullscreen mode

Fun and Creative Uses:

  • ASCII Art: Create basic images using console characters:
console.log("    ____")
console.log("   / _  \\")
console.log("  ( o.o )")
console.log("   \\___/")
Enter fullscreen mode Exit fullscreen mode

ASCII image

  • Simple Animations: Combine console.clear with multiple lines for basic animations.
let position = 0;
const width = 20; // Width of the console "screen"
const speed = 100; // Speed of the animation (in milliseconds)

function animate() {
    console.clear();
    let output = '';

    // Create a string with spaces followed by a dot
    for (let i = 0; i < width; i++) {
        if (i === position) {
            output += ''; // The moving dot
        } else {
            output += ' ';
        }
    }

    console.log(output);

    // Update position
    position++;

    // Reset position to create a looping animation
    if (position >= width) {
        position = 0;
    }
}

// Set an interval to update the animation frame
setInterval(animate, speed);
Enter fullscreen mode Exit fullscreen mode

Animations image

Logging Levels (Browser Dependent):

  • console.log: General information.
  • console.debug: Debugging messages (often hidden by default).
  • console.info: Informational messages.
  • console.warn: Warning messages (usually yellow text).
  • console.error: Error messages (usually red text).
console.log('This is a general information message.');

console.debug('This is a debugging message.');

console.info('This is an informational message.');

console.warn('This is a warning message.');

console.error('This is an error message.');
Enter fullscreen mode Exit fullscreen mode

log image


Thanks for reading, please give a like as a sort of encouragement and also share this post in socials to show your extended support.

Follow for more ⏬

Twitter / Instagram / Github / Youtube / Newsletter / Discord

💖 💪 🙅 🚩
dhanushnehru
Dhanush N

Posted on June 13, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related