Reputation: 11
I have defined a variable named var1 inside the function in javascript but could not access it outside the function. I have referred several solutions in which I got this method to define global variable but it is not accessible outside the function.
function msg1(a) {
window.var1=a;
}
document.getElementById("scores").innerHTML=var1;
Upvotes: 1
Views: 66
Reputation: 1074148
That would work, if you called msg1
before you tried to use var1
.
function msg1(a) {
window.var1 = a;
}
msg1("Hi");
document.getElementById("scores").innerHTML = var1;
<div id="scores"></div>
In general, though, global variables are a bad idea. The global namespace is already far too crowded, it's easy to end up with subtle bugs caused by overwriting (or failing to overwrite) something that's already there. Instead, you can make things global to your code without actually being global, using a scoping function:
(function() {
var var1;
function msg1(a) {
var1 = a;
}
msg1("Hi");
document.getElementById("scores").innerHTML = var1;
})();
<div id="scores"></div>
Upvotes: 2