Bangs (exclamation points) in front of function definitions in Javascript?

author image
By Ben Radler

I recently came across a function declaration with a Javascript syntax that I had never seen before.

!function() {
  // some logic
}

This ! bang is called the unary operator.

I immediately started playing around in the Node console to try and understand this syntax.

Without the bang, this function declaration will actually throw an error:

function() {
 // nothing here
}

// => SyntaxError: Unexpected token (

Weird right? The reason for this is that the function defined with the ! converts what would normally be a function declaration to a function expression. As a result, the function can be invoked without wrapping it in a closure (parenthesis).

In fact, it turns out that our original example is actually identical to the following function declaration:

// original example
!function() {}

// identical example
(function() {})

So you are essentially saving a single character by using the unary operator instead of wrapping the function declaration in a closure.

You can invoke these functions as follows:

// original example
!function() {}();

// identical example
(function() {})();

Thanks to Narciso Guillen for helping decode this syntax.

author image

Ben Radler

Ben is a Software Engineer. He works on autonomous vehicle dispatch at Cruise.

© 2024 benradler.com. I love you.