console.error vs console.log Difference
In this tutorial, we will learn about the difference between console.error and console.log.
console is an object in JavaScript, which has multiple methods to log out objects, strings, numbers, or other messages.
Console is a key tool for front-end developers for debugging purposes. The console.error and console.log are part of the console object.
console error
The console.error is part of the console object and it is used to output an error in the web console.
So what kind of error does it output?
Suppose you are select some DOM element and then apply a CSS class to it. But the element itself doesn't exist in the DOM, then in such case browser will output an error in the web console (or you can manually check and output an error message).
To log out your own error message you can check if the element exists or not. Use console.error and pass an error message if the element doesn't exist.
Example
const element = document.getElementById("id1");
if (element == null) {
console.error("There is an error. Element doesn't exist.");
}
Another scenario is when you can use the console.error are:
- When you fetch some API and it is not reachable.
- While calculating something number is divided by 0.
- While accessing any array and index exceeds array length.
- An object property doesn't exist. and so on.
console log
console.log is the most commonly used console method. It can out all objects, elements, and messages.
console.log is a direct reference to DOM elements so it can interact with DOM elements.
Example
console.log("Hello World!"); // String
console.log(100); // Number
console.log(Math.PI * Math.PI); // Expression
console.log({name: "John", age: 28}); // Object
Difference between console.error and console.log
- console.error is used to output error messages while console.log is the most commonly used console method and is used to log out all sorts of objects or messages.
- In case of some error browser automatically output the relevant error message while you have to manually log out objects using console.log.
- console.error when outputs the error message, it is preceded with a warning symbol while console.log doesn't use any symbol. (visual difference)
- Color and background color of output by the console.error is reddish for it to look like danger while the color of console.log is normal (black). (visual difference)
Conclusion
console.error is the self-generated log to output error messages (can also be used to manually log an error) while console.log is used to log out manually almost any kind of objects or messages.
Also check out difference between console.log and console.dir.