DEV Community

Cover image for Two gotchas in Chrome Developer Tool Console
Sung M. Kim
Sung M. Kim

Posted on • Originally published at slightedgecoder.com on

Two gotchas in Chrome Developer Tool Console

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), await does not work as it needs to be called within an async method.

error in snippet

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

wrapped in async iife

This would be the normal behavior you are expecting but…

You can await in the console without wrapping the statement in an async method~

works in console
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 result in cnosole

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
Can’t map over NodeList object

While you can map over $$
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.

workaround using spread and array from

👋 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 🙂

The post Two gotchas in Chrome Developer Tool Console appeared first on Sung's Technical Blog.

Top comments (0)