1

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;
2
  • Without calling your function, no global variable is created. Commented Jun 16, 2015 at 7:52
  • This seriously sounds like an A-B problem. What, exactly, are you trying to do? Commented Jun 16, 2015 at 7:54

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.