Super useful console.log tricks
Tags: productivity, tooling, javascript, beginners
Published: 2024-06-13 14:00:00

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

```javascript
console.log("Message: Hi Dhanush", 10, true);
```

![multiple values image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p4uj60io3nh7egytcoos.png)

- **Template Literals:** Use template literals for formatted strings:

```javascript
const name = "Dhanush";
console.log(`Hello, ${name}!`);
```

![template literal image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/19fvkx5ci3kz5wt3sgkv.png)


## Formatting and Organization:

- **console.table:** Present data in a neat table format:

```javascript
const data = { name: "Dhanush", hobby: "Chess" };
console.table(data);
```

![console table image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lpmra20n6alf2zwhf3kh.png)

- **console.group/groupCollapsed:** Organize logs with collapsible sections:

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

![console group image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/avu2bify90plrdqsm5bt.png)

- **console.clear:** Clear the console for a fresh start.

![console clear image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8s46ixp772artbwvhy4p.png)

## Advanced Debugging:

- **console.dir:** Get a detailed object structure view:

```javascript
const person = { name: "Dhanush", hobbies: ["youtube", "chess"] };
console.dir(person);
```

![console dir image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zoyms9ko2fq58c6mlllg.png)

- **console.assert:** Log only if a condition fails (useful for debugging assumptions):

```javascript
const age = 18;
console.assert(age >= 21, "User must be over 21");
```

![console assert image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dxqc90igfn5jgt3tw5qf.png)

- **console.count/console.countReset:** Create a counter for tracking occurrences:

```javascript
console.count("API Calls");  // Increments each time called
console.count("API Calls");
console.countReset("API Calls");  // Resets the counter
console.count("API Calls");
```

![console count image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x23r599r4ddme8h3aztn.png)

- **console.time/console.timeEnd:** Measure code execution time:

```javascript
console.time("Loop Time");
for (let i = 0; i < 1000; i++) {
    // Do something
}
console.timeEnd("Loop Time");
```

![console time image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/glixxbh6znm9x94crbya.png)

- **console.trace:** Print a stack trace to pinpoint where an error occurred.

```javascript
function a() {
  function b() {
    console.trace();
  }
  b();
}

a();
```

![console trace image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4s7mhxktr04e7l2g18i9.png)

### Browser Information and Interaction:
console.log(console): Explore the available console methods themselves.

```javascript
console.log(console)
```

![console image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dex7n623e42uthr512b8.png)

- **console.log(navigator):** Access browser information (user agent, language, etc.).

```javascript
console.log(navigator)
```

## Fun and Creative Uses:
- **ASCII Art:** Create basic images using console characters:

```javascript
console.log("    ____")
console.log("   / _  \\")
console.log("  ( o.o )")
console.log("   \\___/")
```

![ASCII image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/87gwctw56p5ruzb62hpn.png)

- **Simple Animations:** Combine console.clear with multiple lines for basic animations.

```javascript
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);
```

![Animations image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hln3m8jhvke2j5hzhj8g.png)

### 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).

```javascript
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.');
```


![log image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rfdmvw9d7y6w17xld43n.png)

---

_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**](https://x.com/Dhanush_Nehru) **/** [**Instagram**](https://www.instagram.com/dhanush_nehru/) **/** [**Github**](https://github.com/DhanushNehru/) **/** [**Youtube**](https://www.youtube.com/@dhanushnehru?sub_confirmation=1) **/** [**Newsletter**](https://dhanushn.substack.com/) **/** [**Discord**](https://discord.com/invite/Yn9g6KuWyA)