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.
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.
1const result = await axios.get(...);
2console.log("Result:", result);
info()
can be used to provide information to the end user on how to use a method correctly.
1console.info(
2 'React Hook "useState" is called conditionally. React Hooks must be called in the exact same order in every component render. (react-hooks/rules-of-hooks)'
3);
warn()
can be used to alert the user that a method's name has changed or it will be deprecated.
1console.warn(
2 "Warning: componentWillMount has been renamed, and is not recommended for use. See https:/fb.me/react-unsafe-component-lifecycles for details."
3);
error()
can be used to report an error encountered in the code.
1console.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.
1console.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!
1const response = await fetch("https://jsonplaceholder.typicode.com/users");
2const statusCode = response.status;
3
4console.assert(statusCode === 200, "Occured an error!");
Occured an error!
Clear logs
The method clears all console messages.
1console.clear();
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.
1for (let i = 0; i < 5; i++) {
2 console.count();
3 console.count("myCounter");
4
5 if (i === 2) {
6 console.countReset();
7 }
8
9 if (i === 4) {
10 console.countReset("myCounter");
11 }
12}
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()
.
1const name = "Enes";
2const age = 21;
3const city = "Bursa";
4const country = "Turkey";
5
6console.group("Person"); // or console.groupCollapsed()
7console.log("Age: ", age);
8console.log("City: ", city);
9console.log("Country: ", country);
10console.groupEnd();
We can also nest the groups.
1const name = "Enes";
2const age = 21;
3const city = "Bursa";
4const country = "Turkey";
5
6console.group("Person");
7console.log("Age: ", age);
8console.group("Location");
9console.log("City: ", city);
10console.log("Country: ", country);
11console.groupEnd();
12console.groupEnd();
Log table
Objects and array can be hard to read in the console. They can visualize it in tabular form.
1console.table(["Turkey", "Italy", "England"]);
1const people = [
2 { firstName: "Kemal", age: 21 },
3 { firstName: "Can", age: 5 },
4 { firstName: "Gürbüz", age: 76 },
5];
6
7console.table(people, ["firstName", "age"]);
1class Product {
2 constructor(name, color, price) {
3 this.name = name;
4 this.color = color;
5 this.price = price;
6 }
7}
8
9const product = new Product("Elbise", "Kırmızı", 299.9);
10
11console.table(product);
1class Product {
2 constructor(name, color, price) {
3 this.name = name;
4 this.color = color;
5 this.price = price;
6 }
7}
8
9const dress = new Product("Elbise", "Kırmızı", 299.9);
10const shoe = new Product("Ayakkabı", "Beyaz", 123);
11const hat = new Product("Şapka", "Siyah", 520);
12
13console.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.
1console.time("myTimer");
2
3for (let i = 0; i < 10; i += 1) {
4 console.timeLog("myTimer");
5}
6
7console.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.
1function mapData(result) {
2 console.trace();
3
4 return {
5 name: result.name,
6 username: result.username,
7 email: result.email,
8 };
9}
10
11async function getResult(response) {
12 const result = await response.json();
13 return mapData(result);
14}
15
16async function fetchData(string) {
17 const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
18 return getResult(response);
19}
20
21await fetchData();
console.trace
overrideMethod
mapData
getResult
await in getResult (async)
fetchData
await in fetchData (async)
(anonymous)
With the happiness of a cool andd amazing friday night, I end this little article here. Take care of yourself.