How I learned to avoid implied globals (and why)
Tags: javascript, webdev, beginners
Published: 2021-03-02 18:19:54

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](https://girlgeek.io/), the [CS department at CCSF](https://www.ccsf.edu/academics/schools/stem/computer-science-department), and, of course, [DEV](https://dev.to/). 

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. 

{% twitter 1337179838818492417 %} 

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](https://dev.to/trydaily/spook-your-colleagues-with-a-halloween-themed-virtual-standup-52m1), in addition to setting up the [video call elements](https://docs.daily.co/docs/embed-the-daily-prebuilt-ui) 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: 
```javascript 
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 
}
```

While this code worked, you might’ve noticed the same thing [Phil](https://dev.to/philmillman) did: 

![GitHub comment suggests using the return value instead of implied global](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vmyzxu209bwia3hu9rgw.png)

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 "TypeError: cannot read property 'number' of undefined at spooky.html"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i5mlz4ok9fq6fkeqfg58.png)

Oh no. Promises. They’re on almost every [interview questions list](https://dev.to/macmacky/70-javascript-interview-questions-5gfi), 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](https://media.giphy.com/media/ToMjGpzjpWhlKkIyiY0/giphy.gif) 

### Promises and async/await 

There are loads of [fantastic articles about JavaScript Promises and async/await](https://dev.to/lydiahallie/javascript-visualized-promises-async-await-5gke) 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: 

```javascript
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);
        }
      }
``` 

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](https://developer.mozilla.org/en-US/docs/Web/API/Window). If someone else wrote `gifs =` somewhere else, that could override the values I actually wanted. 

See what I mean in this codepen. 

{% codepen https://codepen.io/kimberlee/pen/BaLLogx %}

"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](https://media.giphy.com/media/l4FGl9rk3Dp2vfAuQ/giphy.gif)

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 

```javascript 
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);
        );
```

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](https://jvns.ca/blog/good-questions/) 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](https://twitter.com/kimeejohnson/status/1286426590113480705). 

Let me know what things you’re excited about building over [@kimeejohnson](https://twitter.com/kimeejohnson), and especially let me know if you’ll be [building something with video chat](https://www.daily.co/?utm_source=dev&utm_medium=post&utm_campaign=learning0).