Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 1281

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 25, 20242024-11-25T06:40:12+00:00 2024-11-25T06:40:12+00:00

How I learned to avoid implied globals (and why)

  • 62k

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.

beginnersjavascriptwebdev
  • 0 0 Answers
  • 2 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.