Jump to content

How to convert a local variable to a global variable in javascript

I am working with youtube’s API and after it returns a data in JSON, I made a local variable with that JSON data.

Then I wanted to pass that local variable into the global scope. 
I searched on stackoverflow and it says I should do something like this: https://stackoverflow.com/questions/2788159/turn-javascript-local-variable-into-global-variable

 

{window.localVariableName = localVariableName;}

console.log(localVariableName); 
// this should give you the correct value

but in my app this does not work. I still get undefined on the console.

here’s my code

/* 
TODO list

1. need a fetch function to handle HTTP request
2. renderMainVideo() 
3. renderPlaylist()
4. call back function for the click event
*/


/*
Global variables and constants
*/


const key = 'my API key';
const playlistId = 'UUuSrv3qgQA7SSi6R9bWag5A';
var URL = 'https://www.googleapis.com/youtube/v3/playlistItems';

const options = {
  playlistId: playlistId,
  maxResults: 20,
  key: key,
  part: 'snippet'
};



/* 
HTTP request
*/

URL += '?' + Object.keys(options).map((k) => k + '=' + encodeURIComponent(options[k])).join('&');

fetch(URL)
  .then(res => res.json())
  .then(function (data) {
    var mainVideoID = data.items[0].snippet.resourceId.videoId;
    // convert mainVideoID into a global variable
    window.mainVideoID = mainVideoID;

    console.log(data);
    console.log(mainVideoID);
  })

/*
Render main video
 */
//(this returns undefined)
console.log(mainVideoID); 

how do I pass that mainVideoID into the global scope so I can use it in other places of my program?

If it is not broken, let's fix till it is. 

Link to post
Share on other sites

I'm not sure if this is what you mean, but if you declare 'mainVideoID' outside of the fetch, then you should be able to call it globally. It still returns 'undefined' but I don't think that's because something else as the variable should be global now. Try double-checking the youtube api documentation as you may have missed something.

Link to post
Share on other sites

4 hours ago, Squarq said:

I'm not sure if this is what you mean, but if you declare 'mainVideoID' outside of the fetch, then you should be able to call it globally. It still returns 'undefined' but I don't think that's because something else as the variable should be global now. Try double-checking the youtube api documentation as you may have missed something.

I will check youtube API later.

Even I declare mainVideoID in the global scope, it still returns me undefined.

 

942427569_ScreenShot2018-12-30at4_03_23PM.png.45dd5ffce9d1478f900d3f39cad904c6.png

If it is not broken, let's fix till it is. 

Link to post
Share on other sites

1 hour ago, mrchow19910319 said:

I will check youtube API later.

Even I declare mainVideoID in the global scope, it still returns me undefined.

 

942427569_ScreenShot2018-12-30at4_03_23PM.png.45dd5ffce9d1478f900d3f39cad904c6.png

This because JavaScript is asynchronous, the run time is going In to the fetch which it has to wait for the http responce. while it's waiting it moves to the console.log and finally back to the fetch when the promise is resolved.

 

The outside var does contain the data the console.log is called before it's populated.

 

Your screenshot shows this as the log outside is before the log from inside the fetch

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to post
Share on other sites

If you find Promises cumbersome like I do then you can use async functions like this:

(async () => {
    try {
        const res = await fetch(URL);
        const data = await res.json();
        
        let mainVideoID = data.items....
        
        // do whatever
    } catch (e) {
        console.error(e);
    }
})();

`await` waits for the Promise to finish, then either returns the result if the Promise succeeds, or throws an Error if the Promise fails

🙂

Link to post
Share on other sites

7 hours ago, duncannah said:

If you find Promises cumbersome like I do then you can use async functions like this:


(async () => {
    try {
        const res = await fetch(URL);
        const data = await res.json();
        
        let mainVideoID = data.items....
        
        // do whatever
    } catch (e) {
        console.error(e);
    }
})();

`await` waits for the Promise to finish, then either returns the result if the Promise succeeds, or throws an Error if the Promise fails

I agree for one maybe two promises await is fine, but if you go full functional style then a .then chain is a much nicer way.

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×