DEV Community

Cover image for Understanding and Using Javascript Console API
Sonay Kara
Sonay Kara

Posted on

Understanding and Using Javascript Console API

If you like my articles, you can buy me a coffee :)
Image description


The console API is used for debugging, printing messages, and transferring various information to the console, especially in JavaScript runtimes such as browsers and Node.js. But in order to use the console api correctly, you need to know exactly what the console API is.

In this article, I will explain the console API to you. Console API is an object. This object has keys, and when you write a console method, you access the value of a key in the console object.


Now, I will explain to you by coding my own console object so that you can understand the logic of how the log method works in the console API.

const customConsole = {
    log: function(message) {
        const timestamp = new Date().toISOString();
        const output = `[${timestamp}] LOG: ${message}`;
        alert(output); // Displaying the output (replace with console.log in a real scenario)
    }
};

customConsole.log("Hello, this is a custom console log!");

Enter fullscreen mode Exit fullscreen mode

Try to read the code. As can be seen in the code, I created a custom console object and defined a key for this object, and the value of this key is a function. Then I accessed the log key of this object.


As a result, the console API doesn't just have a "log" method. So how many are there? Let's find out now.

Image description

As seen in the photo, the console object has more than one key and the values ​​of these keys. These values ​​are functions.

We can access these functions with the console object.

console.error()
console.warn()
Enter fullscreen mode Exit fullscreen mode

Now let's learn what some of these functions.


1. console.debug()

console.debug , a function in JavaScript used for debugging purposes in the browser console. By default, output from the console.debug() method will not be visible in Chrome developer tools.

Example :

function subtract(a, b) {
    console.debug("subtract function called:", { a, b });
    const result = a - b;

    if (result > 0) {
        console.debug("Result is positive.");
    } else if (result < 0) {
        console.debug("Result is negative.");
    } else {
        console.debug("Result is zero.");
    }

    return result;
}


let result = subtract(10, 5);  
Enter fullscreen mode Exit fullscreen mode

Output :

Image description

output from the console.debug() method will not be visible in Chrome developer tools.


2. console.error()

It is a method used in JavaScript to print error messages to the console. It is used to facilitate debugging when an error occurs. the message may receive special formatting, such as red colors and a error icon.

Example :

async function fetchData(ıd) {
    try {
        const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${ıd}`);

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        console.log("posts data fetched successfully:", data);
        return data;

    } catch (error) {
        console.error(" error posts data :", error.message);
    }
}

fetchData(1);

Enter fullscreen mode Exit fullscreen mode

If there is an error while fetching data, this is the output :

Image description


3. console.warn()

It is a method used in JavaScript to print potential problems or situations that require attentionthe console. It is used to facilitate debugging when an error occurs. the message may receive special formatting, such as yellow colors and a warning icon.

Example :


  if (password.length < minLength) {
        console.warn("Warning: Password must be at least 8 characters long.");
        return false; 
    }
Enter fullscreen mode Exit fullscreen mode

4. console.dir()

The console.dir() method displays a list of the properties of the specified JavaScript object. In browser consoles, the output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects.

Example :

const basket =  {
    name : "t-shirt",
    price : 100,
    quantity : 1,
    color : [ "blue" , "red" , "yellow"],
    size : [ "xs" , "s" , "m" , "l" , "xl"],
    total : function() {
        return this.price * this.quantity;
    }

}

console.dir(basket)
Enter fullscreen mode Exit fullscreen mode

Output :

Image description


5. console.dirxml()

The console.dirxml() method displays an interactive tree of the descendant elements of the specified XML/HTML element. If it is not possible to display as an element the JavaScript Object view is shown instead. The output is presented as a hierarchical listing of expandable nodes that let you see the contents of child nodes.

Example :

console.dirxml(document.body);
Enter fullscreen mode Exit fullscreen mode

Output :

Image description


6. console.assert()

The console.assert() method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens.

Example :

consolle.assert("a" === "f" , error message)
Enter fullscreen mode Exit fullscreen mode

Output :

Image description


7. console.count()

The console.count() method logs the number of times that this particular call to count() has been called.

Example :

function greet(user) {
  console.count();
  return `hi ${user}`;
}

greet("micheal");
greet("roman");
greet();
console.count();
Enter fullscreen mode Exit fullscreen mode

Output :

Image description


Conclusion

If a condition is not true, it prints an error message. If the condition is true, it won't print anything.

Top comments (6)

Collapse
 
kurealnum profile image
Oscar

Just a heads up that you can add highlighting to the code blocks if you'd like. Just change:

code block with no colors example

... to specify the language:

code block with colors example

More details in our editor guide! Also, awesome post!

Collapse
 
sonaykara profile image
Sonay Kara

thanks a lot . I will read the document

Collapse
 
alexroark profile image
Alex Lapikov

.debug is really powerfull method, thank you 🤗

Collapse
 
sonaykara profile image
Sonay Kara

You're welcome.

Collapse
 
benborla profile image
Ben Borla

Wow. I have accustomed to only use console.log, error, and table. Thank you for this!

Collapse
 
prartha_li_cd87eb78a9c0a0 profile image
Prartha

Thanks for sharing! I highly recommend EchoAPI; it has significantly enhanced my JavaScript development experience with its powerful tools for efficient API management.