April 19, 2020
Estimated Post Reading Time ~

Chrome Console Magic

Chrome has many timesaving and neat tools built into it, many of these tools are not necessarily obvious on the surface. This post is a deeper dive into what is available. If you are not familiar with Chrome Dev Tools at all, this post is probably not for you.
$ selectors
Chrome has built-in selectors much like jquery.
Open selectors example file in Chrome
Open dev tools, console
On this page, you will see 3 divs, two with a selector-test class and one with selector-test id.
There are 4 useful types of $ selectors in Chrome.
$()
$() selects the first matching element. (If jquery is active on the page, it will select all matching elements). It will match classes prefaced with ‘.’, IDs prefaced with ‘#’, or regular elements such as ‘p’, 'div', etc.
Example 1 (in the console type): $('.selector-test')

Chrome returns: <div class="selector-test">Test selector content (.selector-test)</div>

Example 2: $('div')

Chrome returns: <div class="selector-test">Test selector content (.selector-test)</div>

The same div is selected in both examples as both the first item with class "selector-test" and the first div on the page.
$$()
$$() selects all matching elements (similar to jquery)
Example: $$('.selector-test')

Chrome returns, the expandable array: [<div class=​"selector-test">​Test selector content (.selector-test)​</div>​, <div class=​"selector-test">​Test selector content (.selector-test)​</div>​]

$_
$_ returns the last valued and returned result. If you did this directly after the last example, it will return the same results ([<div class=​"selector-test">​Test selector content...).
Example: 1+1; //hit enter here so 2 is returned $_ + 2;

Chrome returns: 4 (because 1+1+2 = 4)

$0 - $4
Returns the current or previous inspector selected item. $0 selects the current, $1 previous, $2 item before previous… etc.
Example: [select an item via element/inspector, I’ve selected the h1] $0

Chrome returns: <h1> Selectors</h1>

This can come in handy for things like a copy($0) which copies the current selection to the clipboard.

Screencap of the above exercises.
Advanced console commands
Console.log everything right? Well yeah, obviously, but there are some other alternatives that may help. You may continue to use selectors.html for this section as all of the examples will be done directly in the console, but may also be included in your javascript files in the future.
console.error/console.warn
Much like console.log except with special styling and will note an error or warning in the error/warning count. Console.error also comes with a stack trace, console.warn does not.
Example: console.error('this shouldn’t happen'); console.warn('this probably shouldn’t happen');

Chrome returns:

And notes it in the error/warning count:

console.clear
It seems simple but is relatively unknown.
Example: console.clear();

Chrome returns: "Console was cleared", (also clears error and warning counts)

console.table
This is most useful for displaying xml, JSON, arrays, or similar in a sortable table format.
Example: var newArray = [{a:1, b:2, c:3},{a:2, b:3, c:4},{a:3, b:4, c:5},{randomVar:"woah"}] console.table(newArray);

Chrome returns:

You can also edit which keys you want to be displayed by passing in an additional array.
Example: var newArray = [{a:1, b:2, c:3},{a:2, b:3, c:4},{a:3, b:4, c:5},{randomVar:"woah"}] console.table(newArray, ['a', 'c']);

Chrome returns:

console.groupCollaped/console.groupEnd
This is used for grouping lots of console messages together.
Example: console.groupCollapsed('My condensed messaging'); //loops 49 times, logs msg each time for(i=0;i<50;i++){ console.log('logging number: ' + i); } console.groupEnd();

Chrome returns:

Which expands to reveal all grouped messages:

Message grouping can also be nested.
Example: console.groupCollapsed("nest1"); console.log('message nest 1'); console.groupCollapsed("nest 2"); console.log('message nest 2'); console.groupEnd(); console.groupEnd();

Chrome returns:

console.group
Same as groupCollapsed, except not collapsed by default.
console.time/console.timeEnd
These are used for time tracking. Note that timing is used for estimation purposes only, and should not be considered 100% accurate or used for time-critical syncing. It can be used however for optimization and code efficiency.
Example: console.time("Array initialize"); var array= new Array(1000000); for (var i = array.length - 1; i >= 0; i--) { array[i] = new Object(); }; console.timeEnd("Array initialize");

Chrome returns: Array initialize: 1415.537ms

console.count
This is used similar to the example above for grouping but can work outside separate functions automatically.
Example: function funct1(){ console.count('I am counting'); }; function funct2(){ console.count('I am counting'); }; funct1(); funct2();

Chrome returns: I am counting: 1 I am counting: 2

What happens here is the first function is called and produces the message, then counts and appends how many times that message has been stated. Then the second function is called and does the same, but keeps track of how many times the count expression is called, in this case twice. Note that if you clear the console, this number does get reset.
console.assert
This tests that a condition is met, then show an error message (console.error) if NOT met.
Example 1: var fruit = "orange"; console.assert(fruit!="orange", "Fruit is an orange!");

Chrome returns: Assertion failed: Fruit is an orange!

Example 2: var newArray = [1, 2, 3, 4]; console.assert(newArray.length > 5, "new array length is not greater than 5");

Chrome returns: Assertion failed: new array length is not greater than 5

Example 3: var newArray = [1, 2, 3, 4, 5]; console.assert(newArray.length > 4, "new array length less than 4");

Chrome returns: [Nothing, because assertion is true.]

And console.log?!
Console.log is just a message, what’s there to learn?
Combining complex selectors with messaging:
Example: console.log("Elements on page with .selector-test:", $$('.selector-test'));

Chrome returns:

The key here is the comma. That makes the selector object expandable and elements able to be found in the dom. If the commas were a plus instead, the results would look like this: “Elements on page with .selector-test:[object NodeList]”, which is not as useful if you’re looking for the actual object.
Next, you can style messages:
The ability to use console log vars is built into Chrome, for this example, we are using ‘%c’ which is Chrome’s console inspector formatted styling variable.
Example: console.log(" %c🐜🐜🐜%c What is this a console log for ants? %c🐜🐜🐜", "color:black; background:tan; font-size: 15px", "color:black; background:brown; font-size: 9px", "color:black; background:tan; font-size: 15px");

Chrome returns:

You can see the formatting is similar to css, each “%c” notes a new style in order as comma-separated.
first %c: "color:black; background:tan; font-size: 15px"
second %c: "color:black; background:brown; font-size: 9px"
third %c: "color:black; background:tan; font-size: 15px"
Understand this concept before moving on to the next example.
Overloading with include vars:
There is a number of other % calls that can be used here. The example below is similar to the top although the expandable object is being passed via the ‘%o’ into the console string, this allows you to make complex and expandable strings.
Example 1 (augmented the first example from above): console.log("Elements on page with .selector-test: %o (with auto object in string)", $$('.selector-test'));

Chrome outputs:

Example 2: var conString = "Names" var conInteger = 1.123 var conFloatingPoint = conInteger var conObject = $$('.selector-test') var conJSObject = ["Tumpy", "Clintoc", "Robburn"] console.log("formatted as string: %s \nformatted as Integer: %d \nformatted as floating point: %f \nformatted as dom object: %o \nformatted as JS Object: %O", conString, conInteger, conFloatingPoint, conObject, conJSObject);

Chrome outputs:

It is important to note here that each var is used in the order it is comma-separated to the console.log display string. Meaning if you swap %s and %d in the previous example, it would stringify 1.123/conInteger and attempt to convert “Names” into an integer, which will result in a NaN.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.