Home >Web Front-end >JS Tutorial >Understanding and Using Javascript Console API in Detail

Understanding and Using Javascript Console API in Detail

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 08:22:29278browse

If you like my articles, you can buy me a coffee :)
Understanding and Using Javascript Console API in Detail


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!");

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.

Understanding and Using Javascript Console API in Detail

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()

Now let's learn what some of these functions do.


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

Output :

Understanding and Using Javascript Console API in Detail

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

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

Understanding and Using Javascript Console API in Detail


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 :

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!");


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 :

console.error()
console.warn()

Output :

Understanding and Using Javascript Console API in Detail


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 :

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

Output :

Understanding and Using Javascript Console API in Detail


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 :

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

Output :

Understanding and Using Javascript Console API in Detail


7. console.count()

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

Example :

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

Output :

Understanding and Using Javascript Console API in Detail


Conclusion

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

The above is the detailed content of Understanding and Using Javascript Console API in Detail. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn