Javascript local and global variables

Javascript variables can be local or global scoped depending upon how the are declared. In HTML all global scoped variables becomes part of window object. Here are some variable declaration approaches.

Declaration Global/local Comments
var g1 = “something”;
//outside function
global typical use
g1=”something”;
//outside function
global better to use var
var lv1=”something”;
//inside function
local typical use
g3=”something”;
//inside function
gloval its better to avoid. Or use window.g3 = “something”

Here is an example containing local and global variables.

<script type="text/javascript">
var g1 = "global value1";
g2 = "global value2"; 
function f1() {
  var lv1 = "local value1";
  g3 = "gloval value3";
  document.write("==In function f1==<br/>");
  document.write("g1=" + g1 + "<br/>");
  document.write("g2=" + g2 + "<br/>");
  document.write("g3=" + g3 + "<br/>");
  document.write("lv1="  + lv1 + "<br/>");
}
f1();
document.write("==outside function f1==<br/>");
document.write("g1=" + g1 + "<br/>");
document.write("g2=" + g2 + "<br/>");
document.write("g3=" + g3 + "<br/>");
document.write("typeof(lv1)="  + typeof(lv1) + "<br/>");
document.write("==using window to access global variables==<br/>");
document.write("window.g1=" + window.g1 + "<br/>");
document.write("window.g2=" + window.g2 + "<br/>");
document.write("window.g3=" + window.g3 + "<br/>");
</script>
refresh

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments