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:


{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?

Declare mainVideoID outside of the function and edit it in the function. It will look something like this:

var mainVideoID;

fetch(URL)
  .then(res => res.json())
  .then(function (data) {
    mainVideoID = data.items[0].snippet.resourceId.videoId;
  })

even if I declared mainVideoID in the global scope, if I log it @ the global scope, it still gives me undefined, why though? @LudwigThePig

Put the fetch in a function and assign it to the variable.
Its best practise to avoid polluting the global scope though.

Your code is hitting that last console.log before the promise from the fetch resolves. It is expected that it will show undefined. That doesn’t mean that the global variable isn’t being set when the promise is finally resolved.

2 Likes

I agree with @HarplingeTom.
Try console logging it inside of setTimeout() function and see if it still comes undefined or not.

1 Like

yeah, it works when I put it in a setTimeout() function.

Hey, can you post the finished code? Would help me a lot! Thanks.

please can u send the code