Two gotchas in Chrome Developer Tool Console

featured
April 20, 2019
💫 Originally posted here. Broken? Let me know ~

Photo by Jason Leung on Unsplash

There are two surprising behaviors on Chrome Developer Tool Console (“console” hereafter).

First one was pointed out by my friend Nicolas Marcora that you can await an async method, and second one being $$ (a short-cut for document.querySelectorAll) returning an array, not a NodeList object.

Let’s go over how they are different.

1️⃣ Await in console

Within an editor (I am using a Snippets feature, which is like a scratchpad but works like an editor. You can try it in your favorite editor like, VS Code, Atom, or VIM), await does not work as it needs to be called within an async method.

To get around the issue, you can wrap it in an async method (an async IIFE in this case).

This would be the normal behavior you are expecting but…
You can await in the console without wrapping the statement in an async method~

It’s Magic~~~

It’s a behavior added to Chrome Devtools since Chrome 62, released on year 2017.

So this is a nice feature but you have to watch out as you can’t simply paste your code in your editor.
It needs to be wrapped inside an async method.

2️⃣ $$ vs document.querySelectorAll

$$ is a part of Console Utilities API, which is available only within the console and not part of either JavaScript or DOM.

Google document describes $$ as

$$(selector) returns an array of elements that match the given CSS selector. This command is equivalent to calling document.querySelectorAll().

https://developers.google.com/web/tools/chrome-devtools/console/utilities#queryselectorall

The documentation says it’s equivalent to calling document.querySelectorAll() but $$ is differs
where document.querySelectorAll() returns a NodeList object while $$ returns an array.

NodeList is an array-like object, whose prototype doesn’t inherit from Array.prototype. That means, a NodeList object instance doesn’t have access to methods such as Array#map or Array#reduce.

Can’t map over NodeList object
While you can map over $$

This can cause a problem when you copy & paste code using $$ selector and simply convert it to using document.querySelectorAll() and try to call Array.prototype

You can easily convert a NodeList object to an array using a spread syntax or Array.from by the way.

👋 Parting Words

The console can save you a lot of keystrokes but you might want to double check before copying & pasting the code from console to the editor.

If you have more gotchas please let me know 🙂