Enumerability in JavaScript, or “why some properties are dimmed in a console.log”

Posted March 6, 2018 in Research, Web Development

This rabbit hole began as I was investigating wp, the global object for WordPress’ JavaScript API. If you open up the console on this page and type wp, you’ll see a couple of entries. If you do that while viewing a page in the admin, you’ll see a whole lot more and on a page running Gutenberg, you’ll see something like this:

A screenshot of the wp object in the JavaScript console

Scrolling down towards the end of the blocks property, the one I was investigating, I saw something strange:

Detailed view of the blocks property showing entries dimmed and prefixed with get

It looked like each method inside of blocks was duplicated, dimmed, and prefixed with get. I decided to dive into this rabbit hole, and started with:

Why are some properties dimmed in a console.log‘d object?

I’d seen dimmed properties before, and I always thought of them as the properties that are there by default, or ones I’m not supposed to manipulate. It turns out that’s pretty much correct. The technical term for that is that dimmed properties are non-enumerable vs. enumerable properties.

What? This StackOverflow post both identifies the circuitousness of the MDN answer to this question and provides a relatively satisfactory answer. The thing is, sometimes you don’t want every property in an object to be acknowledged when you are looping through an object or an array, and enumerability is the technical word for that.

Spoiler alert: deep down, an array is an object! Learn more about the built-in data types in JavaScript from my spirit guide, Kyle Simpson.

An array is a great example of what’s enumerable and what’s non-enumerable. When you console.log an array, you will see a property for length as well as the expected array entries. We don’t assign the length property ourselves, it is provided by JavaScript, and it doesn’t print when we loop through the entirety of the array.

length is non-enumerable:

Looping through an array of integers with a for..in loop. The dimmed, or enumerable, length property is highlighted.

This rabbit hole could go much much deeper, but for now I need to get back to my research and figure out what that get prefix before the blocks means (something to do with getters and setters, I think).

But before I go, a shoutout to the work of Safia Abdalla who blogs about great little development tidbits. Her curiosity and gusto for blog posts are contagious!

Lastly, these resources helped me out: