DEV Community

Cover image for `throw` objects and functions
Aravind Balla
Aravind Balla

Posted on

`throw` objects and functions

Did you know you could throw objects/functions in Javascript? Objects mean, useful objects for the program to run, not only useful for debugging. Here's a very short one for you!

Lets look at simple code demonstrating a not-at-all-useful cache.

    const cache = new Map();

    const read = key => cache.get(key);

    const store = (key, value) => {
      cache.set(key, value);

    const fakeExternalRes = key => Math.random(0, 888);

    const readResource = async key => {
      let value;

      // try reading from cache
      // if not found, fetch it from external resource
      try {
        value = read(key);
        if(!value) throw key;
      } catch (key) {
        value = fakeExternalRes(key);
        store(key, value);

      return value;

    store('asdf', 'world');


Here, we threw the key and caught it to actually fetch it from external resource and store in the cache. Kinda cool way.

One gotcha here is, we generally use throw for exceptions and not in normal good case scenarios. So we have to make sure that we don't disturb that mindset for fellow members in the team.

This is used in react-cache package by the Facebook team. I have just demonstrated a very simple thing with this. But you can check out the below link for how they have implemented.

Take care.

Top comments (1)

aravindballa profile image
Aravind Balla

That doesn't have a catch. But it handles it in the then part.