0

A beginner question indeed but can't find anywhere on stackoverflow that actually solves this, so any help would be really appreciated. I just want to define a private variable and then return it to the global scope.

In this example, I can access x in the JS console after refreshing the page - but the script runs before the body loads (source at end of head tag) and I cannot create elements that relate to the body content since they haven't loaded yet:

var x = 5;

window.onload = function() {
    var y = 10;
}

I cannot access variable y, presumably because it's a private variable that's not available on the global scope (am I actually correct here?). Using return fails. I just want to be able to create variables from the body, but I can't because the script hasn't loaded in time.

How can this be achieved? I actually can't solve this presumably simple problem. Thanks for any help here.

user8758206
  • 2,106
  • 4
  • 22
  • 45
  • Possible duplicate of [How to execute a function when page has fully loaded?](https://stackoverflow.com/questions/1033398/how-to-execute-a-function-when-page-has-fully-loaded) – ksav Jan 09 '19 at 21:43
  • Depending on how you're trying to access y your assumption that you can't access it because it's private may not be the whole truth... If you try to console.log(y) outside of a window.onload function it will execute before y is defined – WilliamNHarvey Jan 09 '19 at 21:45

4 Answers4

2

A simple way that I use when I need a variable in my console, is assigning them to window like this:

window.y = y;

Then in your console, y as well as window.y will be that variable :)

Michiel Dral
  • 3,932
  • 1
  • 19
  • 21
2

Declare y in the global scope and initialize it in the onload function.

var x = 5;
var y;
window.onload = function() {
    y = 10;
}
ulvesked
  • 429
  • 3
  • 11
1

You could create a global namespace and add properties later to it.

var namespace = Object.create(null); // empty object without prototypes

window.onload = function() {
    namespace.y = 10;
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You obviously can't access y outside of a window.onload function like this, since the window hasn't loaded by the time you check what y is.

var x = 5;

window.onload = function() {
    var y = 10;
}

console.log(y)

Assuming you don't mean that and you're just using onload as an example of a function, you can use window.y as a substitute for var y and it will be global on the window, so you can use it outside of the function.

var x = 5;

function define_y() {
  window.y = 10;
}

window.onload = function() {
  define_y();
  console.log(y);
}
WilliamNHarvey
  • 2,335
  • 2
  • 17
  • 26