Why am I just finding out about #region?

About a 3 minute read

Written by on

#codequality #vscode

As a developer, I try to stay in a continuous learning mentality. Ya know, constant improvement. Great, right?

Well, every once in a while something comes along and makes me think “How in the hell did I not know this before?!”

Today.. that’s #regions.

What’s a #region?

It’s a way of wrapping sections of code so that it can be collapsed together. A simple concept, but freakin’ awesome. Is it going to help you write better code? Probably not, but it’ll definitely help with organization. Instead of just being able to collapse condition statements or functions, you can collapse whatever groups you designate.

For instance, you can bundle your private variables together and make them collapsible.

What’s it look like?

That’s where it gets a little weird. Not only are #regions IDE specific, but they are also different depending on the language. I use VSCode, so I’m going to give examples that work in that editor.

Let’s start with HTML:

<!-- #region Region Name -->
<div></div>
<div></div>
<div></div>
<!-- #endregion -->

If you threw this into VSCode, you would be able to collapse the HTML to the starting region. You’ll also notice “Region Name”; this can be whatever text you’d like to help identify the region.

As said previously, the syntax changes based on the language. Specifically, the comment syntax of the language.

Here’s CSS:

/* #region Region Name */
.foo {
    color: blue;
}
.bar {
    color: pink;
}
/* #endregion */

JavaScript:

// #region Region Name
let foo = true;
const bar = false;
// #endregion

PHP:

#region Region Name
$foo = true;
$bar = $foo;
#endregion

Pretty cool, right?

What’s next?

Take this newfound knowledge and set out on the journey of foldable code.

For my purposes, the default region folding in VSCode has been well enough. However, I did see that there is an extension that may be useful for expanding the capabilities of regions. For example, being able to set a region’s default state to collapsed.

Happy code folding!