Sunday, 19 February, 2017 UTC


Summary

Do you know about console.table()? Here we will learn to add styles to our javascript console output. We will also learn about advanced console tricks to debug better. I will ask you to use chrome for this. Let’s jump into this right now.
Console Tricks with Same old console.log()
Most of us seen how facebook warns people not to paste any code inside the javascript console. If you yet not seen that now its time to do the same. There is nothing fancy going on here. We can add CSS styles to our console output. Open the javascript console (ctrl + shift + I) and paste the following code.
console.log("%cWe are hiring. Join Us!", "font-size:50px; color: red");
Is not it a cool way to attract attention?
Now say you have array of objects like this one
var arr = [{
  name: "Sandeep Acharya",
  age: 22,
  email: "[email protected]"
}, {
  name: "Sandeep Acharya",
  age: 22,
  email: "[email protected]"
}, {
  name: "Sandeep Acharya",
  age: 22,
  email: "[email protected]"
}];
console.table(arr);
Now try to print this one with console.table(arr) You should see a table eye soothing structure like this one
There are different console methods for different situations like
  • console.debug() – For debug – Blue text
  • console.warn() – Warning – Yellow Text
  • console.error() – Error occurred – Red Text
You should probably start using above methods in your javascript code to properly differentiate log messages.
 
 
 
Now let’s say you have three different objects.
You can print them all in a single console.log by separating them using commas.
var a = "I do not know";
var b = 143;
var c = new Object(); 
// In a single log statement
console.log(a, b, c);
Test a new javascript library in a console
I can always try different javascript library without creating an HTML file. Just open your console and paste this. Obviously, you need to change the CDN URL with your desired library’s CDN.
var cdn = "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js";

var script = document.createElement('script');
script .src = cdn;
document.getElementsByTagName('head')[0].appendChild(script);

// Now Test the library methods
// yes we have lodash loaded in the console

var array = [1, 2, 3];
_.reverse(array); // Ouput: [3, 2, 1]
Thus you can check any library quickly.
Thank you for reading this article. If you have any tricks to share please comment here. I will try to add them here.
The post Five Must Know Javascript Console Tricks in 2017 appeared first on Apply Head.