DEV Community

Cover image for How I learned to avoid implied globals (and why)
Kimberlee Johnson
Kimberlee Johnson

Posted on

How I learned to avoid implied globals (and why)

Before I started drafting pull requests, I used to draft press releases. My public relations background comes in handy in my DevRel role today, and it helps me keep learning, too. I’m a community-taught developer, picking up a lot of my technical skills from people I meet in communities like Girl Geek Dinner, the CS department at CCSF, and, of course, DEV.

Today, I’m lucky and grateful to also learn on the job, from colleagues patient enough to teach me best practices. In the spirit of Laurie’s tweet, I’m going to try to do a better job of sharing what they teach me.

This post is my first pass at that! Read on to learn how I learned to be less afraid of spooky JavaScript Promises, to avoid implied global variables, and to get better at bridging the gap between what I know and what my colleagues can teach me.

Spooky Promises from scary code

When I built a Halloween themed video call demo to prank the team, in addition to setting up the video call elements my main run() function needed to retrieve a list of gifs from the Giphy API, and then to plop a random gif on the page.

Here’s the original code I wrote to do that:

async function run() {     
   getGifs();
        setInterval(() => {
          try {
            let url =
              window.giphs.data[Math.floor(Math.random() * 50)].images.original
                .url;
            document.getElementById('bday').src = url;
          } catch (e) {
            console.error(e);
          }
        }, 20 * 1000);
// Some other things happen here too 
}
Enter fullscreen mode Exit fullscreen mode

While this code worked, you might’ve noticed the same thing Phil did:

GitHub comment suggests using the return value instead of implied global

If you’re at a similar spot in your programming journey to where I was before I wrote this post, your first thought reading his comment might’ve been, "Oh! I just need to store the return value of getGifs inside a variable."

This first attempt led to bad news bears, or, a lot of pending Promises in my spooky.html:

Console errors read repeatedly

Oh no. Promises. They’re on almost every interview questions list, but I somehow got this job even though I’m still a bit scared seeing these errors, what am I even doing?!?

Better stop that narrative and take a breath. And then take a Google.

Gif magnifying glass searches bar

Promises and async/await

There are loads of fantastic articles about JavaScript Promises and async/await out there. The part I needed to understand to fix my code, the part that Phil helped surface from the noise, is that the async/await pattern is syntactic sugar on top of Promises.

While I got the async part of the pattern ahead of my async function run(), I forgot the await. Await, well, tells a function to wait on the next step until a Promise resolves. I saw all those {<pending>} Promises because await was missing.

With that fixed, I could focus on specifying return values and replacing implied global variables.

Variable scope and unpredictable consequences

It’s helpful for me to trace back every step a function makes, so I went back to my getGifs() function:

async function getGifs() {
        try {
          const token = '<INSERT_GIPHY_API_KEY_HERE>';
          const giphyEndpoint = `https://api.giphy.com/v1/gifs/search?api_key=${token}&q=halloween&rating=pg`;
          let response = await fetch(giphyEndpoint);
          gifs = await response.json();
          return gifs;
        } catch (e) {
          console.error(e);
        }
      }
Enter fullscreen mode Exit fullscreen mode

It’s not just my run() function, that was missing variable declarations. gifs = await response.json() in getGifs() is missing one too.

When I called getGifs() in run(), I was telling the function to create a side effect and change the state of a global variable on the window object. If someone else wrote gifs = somewhere else, that could override the values I actually wanted.

See what I mean in this codepen.

"Color circles" fills the initial circle colors. Since we didn’t scope the colors as variables within the colorCircles() function, they became global variables on the window object. That means we can "accidentally" override() them in the next function, and reset() them too.

While that side effect works for the purposes of an example codepen, keeping track of the colors as they get swapped is still hard enough to follow. It's like Elle Woods said:

Elle Woods quote Whoever said orange was the new pink was disturbed

Consequences of implied globals can be greater in larger applications, or even when it comes to picking gifs to prank your colleagues.

Final code and final takeaways

let gifSearchResults = await getGifs();
          setInterval(() => {
            try {
              let url =
                gifSearchResults.data[Math.floor(Math.random() * 50)].images.original.url;
              document.getElementById('gifs').src = url;
            } catch (error) {
              console.error(error);
            }
          }, 20 * 1000);
        );
Enter fullscreen mode Exit fullscreen mode

In the final code, I’m using the actual response object from my call to getGifs(). Now, if I want, I can reuse the function in other places, pass in specific search parameters, and use multiple instances of the return object instead of just one globally. Best of all, the state outside of the object won’t get accidentally mutated.

After this code review, I know a bit more about how async/await works and principles of good functional programming. Beyond that, I also learned:

  • Digging around before asking other devs for help can lead to better debugging and faster learning (Julia Evans’ post describes this well!).
  • That said, sometimes sharing learnings in progress can be good too! When I shared my first pass at what I thought I learned with Phil, he helped point out the most important parts.
  • Even "silly" projects can teach you useful things. Because I built an app that picked random Halloween gifs, I now better understand why mutating state outside of a function itself is Bad Functional Programming.

Follow your heart! Build what’s fun! Like my friend Chloe says, it’s all digital crafting.

Let me know what things you’re excited about building over @kimeejohnson, and especially let me know if you’ll be building something with video chat.

Top comments (1)

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

The easiest way to understand promises might be to just implement them:

Let's say we have a function run_then_callback(callback), which does some work asynchronously and then calls its callback. We could wrap this function like this:

function run_then_promise() {
   // our rudimentary custom promise
   let promise = {}

   // a `then` method to set the success callback
   promise.then = (callback) => { promise.resolve = callback }

   // a default callback in case `then` is never used
   promise.resolve = () => console.log("Nothing happens...")

   // call the function, with a callback that defers to the promise
   run_then_callback( () => promise.resolve() )

   // return the promise to the caller
   return promise
}
Enter fullscreen mode Exit fullscreen mode

Now we can call this function and it will already look a surprising lot like JavaScripts promises.

run_then_promise().then( () => console.log("Something happens!") )
Enter fullscreen mode Exit fullscreen mode

From there, there's some obvious refactoring to be done, like creating an actual promise class and move most of this logic in there.

That's really all there is to the core idea; everything else is just fluff, like being able to chain promises and stuff. Of course, they also have extra logic for when a callback returns a new promise, for error handling, etc. But none of that really changes the principle.