Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

I've been reading Jake's guide on custom elements and when/where to define a new custom element. It's a good and quick read, so go check it out!

His final custom element snippet includes something I haven't seen before.

class MyElement extends HTMLElement {
  // Static class property
  static tag = "my-element";

  // Static class method
  static define(tag = this.tag) {
    // ...
  }

  // ๐Ÿ‘‡ What's this is?
  static {
    // ...
  }
}

The class defines two static class members. One is a class property (tag), and the other is a class method (define). Both static class members can be called without initializing the class and creating an instance.

class MyElement extends HTMLElement {
  static tag = "my-element";

  static define(tag = this.tag) {
    console.log('define was called...')
  }
}

// access the `tag` property without initializing a new class instance
console.log(MyElement.tag); // 'my-element'

// call the `define` method without initializing a new class instance
MyElement.define(); // 'define was called...'

Cool, that's what static is for. But what's up with this nameless static block?

Apparently, JavaScript classes support static initialization blocks. These initialization blocks are called during class initialization (don't confuse them with when you initialize a new object of a class).

So, whenever the JavaScript parser rolls over and parses the class MyElement, it'll call its static block. That's neat!

class MyElement extends HTMLElement {
  static {
    console.log('class was initialized...')
  }
} 

// automatically logs "class was initialized..."

Static initialization blocks can be extremely handy for conditionally registering custom elements (as Jake showed) or dynacially (uhm... dynamically?! ๐Ÿ˜…) setting up a shared property across class instances. I could think of a shared database connection or something like this.

But can we all use static initialization blocks today?

MDN Compat Data (source)
Browser support info for Class static initialization blocks
chromechrome_androidedgefirefoxfirefox_androidsafarisafari_iossamsunginternet_androidwebview_android
949494939316.416.417.094

Apparently, static initialization blocks have been part of ECMAScript 2022, and they're supported across all browsers. Well, today I learned!

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly โ€” Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles