Can someone explain why the alert returns "undefined" instead of "hello"?
window.onload = function() {
var a = 'hello';
alert(window.a);
}
Can someone explain why the alert returns "undefined" instead of "hello"?
window.onload = function() {
var a = 'hello';
alert(window.a);
}
variable 'a' is not part of window in your context.
a is scoped to the anonymous function you've assigned to onload.
you COULD add a as a member of window if you wanted:
window.onload = function() {
window.a = 'hello';
alert(window.a);
}
but i'd suggest against doing so.
"Named variables are defined with the var statement. When used inside of a function, var defines variables with function-scope." - (source)
To be accessible globally, and particularly to make a
a member of the window
object, alter your code in this way:
var a; // defined in the global scope
window.onload = function() {
a = 'hello'; // initialized
alert(window.a);
}
Or in this way:
var b = 'world'; //defined and initialized in the global scope
window.onload = function() {
alert(window.b);
}