August 11, 2024

/ ~

Exploring Web APIs: Console

I have created to create mini-series about browser. We will focus on the Web API. Before we start the article, let’s clarify what we mean by calling everything an API.

API (Application Programming Interface) refers to structures that are used to access the features provided by the browser and contain methods/parameters. I like to simplify definitions.

You have used many API so far; console object for logging, window object to access the browser page and fetch method to make HTTP requests etc. In this article, we will take a look at the Console API (of course it’s not just console.log).

Log methods

Let’s start with the basics. The logs that we print in our application can have various meanings. For example, we can alert the user to use another function, report an error, or provide information about the result.

log() can be used to see the current status of the variable.

Terminal window
const result = await axios.get(...);
console.log("Result:", result);

info() can be used to provide information to the end user on how to use a method correctly.

Terminal window
console.info(
'React Hook "useState" is called conditionally.'
);

warn() can be used to alert the user that a method’s name has changed or it will be deprecated.

Terminal window
console.warn(
"Warning: componentWillMount has been renamed, and is not recommended for use. See https:/fb.me/react-unsafe-component-lifecycles for details."
);

error() can be used to report an error encountered in the code.

Terminal window
console.error('SyntaxError: /src/App.js: Unexpected token, expected "(" (5:2)');

debug() can be used to view variables in real-time while developing. Unlike console.log, it does not appear in the console by default. To show it in Chrome, the verbose log level must be selected.

Terminal window
console.debug("I couldn't find any example for this case...");

If we look at how they appear on console;

We don’t use the others as much as console.log. But if we consider that we write a package, we want to make sure that the user understands any error or warning correctly.

Assertion

We can use this method to print a log when spesific conditions are met. If the first parameter is false, the second parameter will print. Soooo, no need to use if statements anymore!

Terminal window
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const statusCode = response.status;
console.assert(statusCode === 200, "Occured an error!");
Occured an error!

Clear logs

The method clears all console messages.

Terminal window
console.clear();

This method works in the browser but you may notice it doesn’t work in the Node terminal. If you are looking for an alternative, you can use process.stdout.write('\033c'); for clear stdout.

Countable log

Here is a gooood one. No need to create a variable anymore to count how many times a code block is executed. count() method takes care of that itself. We can use countReset() to reset the counter. And the label parameter can be used to customize counters.

Terminal window
for (let i = 0; i < 5; i++) {
console.count();
console.count("myCounter");
if (i === 2) {
console.countReset();
}
if (i === 4) {
console.countReset("myCounter");
}
}
default: 1
myCounter: 1
default: 2
myCounter: 2
default: 1
myCounter: 3
default: 2
myCounter: 4
default: 3
myCounter: 1

Grouping logs

Sometimes output can be related and it can be difficult to exemine logs. We can group logs using group() and groupCollapsed(). To end the grouping, we can use groupEnd().

Terminal window
const name = "Enes";
const age = 21;
const city = "Bursa";
const country = "Turkey";
console.group("Person"); // or console.groupCollapsed()
console.log("Age: ", age);
console.log("City: ", city);
console.log("Country: ", country);
console.groupEnd();

We can also nest the groups.

Terminal window
const name = "Enes";
const age = 21;
const city = "Bursa";
const country = "Turkey";
console.group("Person");
console.log("Age: ", age);
console.group("Location");
console.log("City: ", city);
console.log("Country: ", country);
console.groupEnd();
console.groupEnd();

Log table

Objects and array can be hard to read in the console. They can visualize it in tabular form.

Terminal window
console.table(["Turkey", "Italy", "England"]);
Terminal window
const people = [
{ firstName: "Kemal", age: 21 },
{ firstName: "Can", age: 5 },
{ firstName: "Gürbüz", age: 76 },
];
console.table(people, ["firstName", "age"]);
Terminal window
class Product {
constructor(name, color, price) {
this.name = name;
this.color = color;
this.price = price;
}
}
const product = new Product("Elbise", "Kırmızı", 299.9);
console.table(product);
Terminal window
class Product {
constructor(name, color, price) {
this.name = name;
this.color = color;
this.price = price;
}
}
const dress = new Product("Elbise", "Kırmızı", 299.9);
const shoe = new Product("Ayakkabı", "Beyaz", 123);
const hat = new Product("Şapka", "Siyah", 520);
console.table([dress, shoe, hat], ["name", "color", "price"]);

Time log

Sometimes we want to measure the execution time of a piece of code. We can take dates and get difference in the old way. However browser has a method for this. We use time() to start the timer, timeLog() to print current value and timeEnd() to stop it.

Terminal window
console.time("myTimer");
for (let i = 0; i < 10; i += 1) {
console.timeLog("myTimer");
}
console.timeEnd("myTimer");
myTimer: 0.003173828125 ms
myTimer: 0.06396484375 ms
myTimer: 0.08984375 ms
myTimer: 0.114013671875 ms
myTimer: 0.135009765625 ms
myTimer: 0.154052734375 ms
myTimer: 0.196044921875 ms
myTimer: 0.2119140625 ms
myTimer: 0.23193359375 ms
myTimer: 0.251953125 ms
myTimer: 0.27392578125 ms

Trace

We use to see which functions were called and in what order until a function was called.

Terminal window
function mapData(result) {
console.trace();
return {
name: result.name,
username: result.username,
email: result.email,
};
}
async function getResult(response) {
const result = await response.json();
return mapData(result);
}
async function fetchData(string) {
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
return getResult(response);
}
await fetchData();
console.trace
overrideMethod
mapData
getResult
await in getResult (async)
fetchData
await in fetchData (async)
(anonymous)

With the happiness of a cool and amazing friday night, I end this little article here. Take care of yourself.

Resources