You will have to use %c
with each occurrence accompanied by an argument that expresses the styling that you desire
console.log(
'%c Object A instantiated %c before B !! ',
'background: white; color: red',
'background: red; color:white'
);
Note that you could use any CSS property under the sun into as an argument. In case of the above string this is how it renders out
Use this when you want to print an array of objects For example if you want to print this :
const arrayOfBooks = [
{ title: 'Heart of Darkness', author: 'Joseph Conrad' },
{ title: 'A Walk in the Woods', author: 'Bill Bryson' },
{ title: 'Rich Dad Poor Dad', author: 'Robert Kiyosaki' }
];
then y'all know what console.log(arrayOfBooks)
does
But if you instead use:
console.table(arrayOfBooks)
you'll get the following output:
Isn't it at least 300 times nicer and easier to infer what the array is ?
HOLD TIGHT FOLKS ! Before you leave to try this out yourself in the console let me tell you that this one is NOT natively available to Javascript in the browser
You will have to first load this JS resource from the CDN using the below script tag :
<script src='https://raw.githubusercontent.com/adriancooney/console.image/master/console.image.min.js'></script>
For more details on ☝️ , refer this link. Obviously the project isn't maintained anymore (the last commit is like 6 years ago) because there isn't really anything more to console.image
:)
BONUS : You get console.meme
included in the CDN to make something like this :
And the format for that as per their Github Readme is:
console.meme(upper text, lower text, meme type|url, width, height)
You can use this to sort of indicate log messages that show the devs it's not really something that breaks the project but good to fix it in the future commits
console.warn('Image Kirk_0932.jpg dimensions are slightly off and its causing a small part to be hidden from the user')
and here is a screenshot of how ⚠️ WARNING messages look like inside the console
You can keep track of how much time api calls take to fetch data right in the console. You can use this to find out average time and if you think it suxx, you can bug your backend dev ;P
So pass in the same label 'API_TEST'
to time
and timeEnd
functions for it to work.
console.time("API_TEST");
const fiftyTests = Array.from(
{ length: 50 },
() => fetch('https://jsonplaceholder.typicode.com/todos/1'));
for(const prom of fiftyTests) {
const resp = await prom;
const json = await resp.json();
console.count('Fetched ');
}
console.timeEnd("API_TEST");
Now you can see the time it takes to make api calls 50 times one - after - the - other printed in your console.
You can now divide it by 50 to get the average time the API takes to respond.
⚠️ Don't use Promise.all() because it will simultaneously await all promises and tell you once everything has resolved which defeats our purpose