DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Updated on

The curious case of the Empty Statement

Did you know there's such a thing as an empty statement in JavaScript? It's true! An empty statement is denoted by a semicolon:

;
Enter fullscreen mode Exit fullscreen mode

Here are some examples of using empty statements IRL:

for (let i = 0; i < arr.length; i++) ;
Enter fullscreen mode Exit fullscreen mode
if (true) ;
Enter fullscreen mode Exit fullscreen mode

In JavaScript, a semicolon is used to terminate a statement. If no actual statement precedes the semicolon, the JS engine will omit executing any code where a statement would be expected. So in these 2 examples, our use of ; in place of the expected statement is considered an empty statement and has no effect.

In searching for a use case for the empty statement, it seems to be used similarly to when empty functions are used for no operation (or "noop") scenarios (Empty functions are often used when you need to satisfy an argument to a function call without actually wanting the supplied function to do anything).

Here's an example of where it could make sense to use an empty statement (although I personally think this should be refactored to something different altogether, but just to demonstrate the potential use...):

let myVar = 4;

if (myVar < 4) {
  foo();
} else if (myVar > 4) {
  bar();
} else if (myVar === 4) {
  ; // Do nothing
} else {
  throw new Error('Error!');
}
Enter fullscreen mode Exit fullscreen mode

With this example, if we omitted the empty statement conditional then the error would be thrown (assume we don't want that), so here we're simply adding another condition to perform no action if the value of myVar is exactly 4.

An empty function could be used in place of the empty statement but I suppose you save a few characters worth of memory. πŸ˜‰

While the empty statement can have this kind of use, I would caution against using it since it can have some unintended consequences:

if (isReady);
  load();
Enter fullscreen mode Exit fullscreen mode

In this example, it might look like the load function will be called only if isReady is truthy, but since we're using an empty statement, the value of isReady is irrelevant and load will always be called.

So if you do employ the use of empty statements, it would be ideal to call out its intentional use with a comment so as not to trip up others or yourself.

Have you seen a good use case where empty statements are handy? If so, please share!

Resources

MDN Article on Empty Statement


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter!

Top comments (0)