idude
idude

Reputation: 4922

Window.onload Scope

Let's say I have the following code:

var x;
window.onload = function(){
   x=4;
};
console.log(x);

The console doesn't output 4, but undefined.

Does anyone know how I would be able to access the changed x variable outside of the window.onload function?

Thanks in advance!

Upvotes: 1

Views: 817

Answers (2)

Nhân Nguyễn
Nhân Nguyễn

Reputation: 132

window.onload() means after DOM tree are loaded, this function is run. So, console.log(x) will be ran before window.onload() run

Upvotes: 3

Kilenaitor
Kilenaitor

Reputation: 664

This has to do with javascript's async behavior. The console.log doesn't happen after the window.onload has fired. They're separate events. If you want it to output the x, you need to do

var x;
window.onload = function(){
   x=4;
   console.log(x);
};

Upvotes: 4

Related Questions