Guards using invariant in JS
Tags: javascript, programming, webdev, beginners
Published: 2022-02-03 08:30:21

## Intro
Have you ever heard this quote? 👇
> If you want to be the best, learn from the best.

I believe that it strongly applies to programming skills 💻

So in this series, we'll gradually learn top-notch JS from famous open-source projects!

## 👉 Today's topic - guards using invariant 🛡️

Guard is a great way to handle errors and prevent bugs in your code.
And combined with invariant it becomes an even more powerful and versatile technique 💪

### 👉 First of all, what is a guard?

Guard is just validation:
- The guard checks a specific condition
- If the condition draws to true, the guard prevents some functionality from executing

```js
function handleInput(input) {
  const isInvalid = !input || typeof input !== 'string';

  // Here it is!
  if (isInvalid) {
    throw new Error('Input is invalid');
  }
  
  return getProcessedInput(input);
}
```

### 👉 Okay, I'll use them!

There is an issue with using guards like this.
It forces you to repeat throw new Error in dozens of places.
So, for example, if you want to add simple logging, you have to update all guards in all places.

```js
function handleInput(input) {
  const isInvalid = !input || typeof input !== 'string';

  if (isInvalid) {
    console.log('Input is invalid'); // <- add this in all places  
    throw new Error('Input is invalid');
  }
  
  return getProcessedInput(input);
}
```

### 👉 How to do it like a top-performer?

React developers faced the same issue and added [special invariant abstraction](https://github.com/facebook/react/blob/v17.0.0/packages/shared/invariant.js) to resolve it.

It does the same thing while preserving the DRY principle.

```js
function handleInput(input) {
  const isValid = input && typeof input === 'string';
  
  invariant(isValid, 'Input is invalid');
  
  return getProcessedInput(input);
}
```

### 👉 How does invariant work under the hood?

[The most popular JS invariant implementation](https://www.npmjs.com/package/invariant) takes multiple arguments:
- condition, that defines whether an error needs to be thrown
- format, simply put, the error message
- six optional arguments to be placed instead of %s inside the format

```js
invariant(
  1 > 2, 
  'Hello from error. %s %s %s %s %s %s',
  1, 2, 3, 4, 5, 6
);

// Results to
// > Uncaught Error: Hello from error. 1 2 3 4 5 6
```

### 👉 Let's re-implement it!

As always, let's re-create invariant ourselves to get an in-depth understanding of its inner workings.

Our version uses modern ES6+ syntax and supports an indefinite number of optional arguments.

```js
const invariant = (condition, format, ...args) => {
  if (!condition) {
    if (!format) {
      throw new Error('General error occured.');
    }

    let i = 0;

    throw new Error(format.replace(/%s/g, () => args[i++]));
  }
};
```

### 👉 Implement it yourself!

Go to [my CodeSandbox](https://codesandbox.io/s/invariant-zo6rp?file=/src/index.js) and try to implement the invariant function, based on what we just learned.

---

P.S. [Follow me on Twitter](https://twitter.com/fromaline) for more content like this!

{% twitter 1485684303891771393 %}