How to access global variable in JavaScript

Accessing global variable in JavaScript, what is global variable where it used.
Global variable is accessible everywhere in the script, for example if you want to access variable which defined in top.

<script language="javascript">
// declaring global variable 
var myVariable = 1;

Its accessible inside the function or outside the function as variable.
there is a method call window.variable which will be same as calling the variable inside the function.

Let’s see little detail about it, we are declaring variable call “myVariable” in top.And creating one function call sumValue which will return myVariable+arg value.

// We are going to create simple function which will return sum value
function sumValue(arg) {
	// two way we can access the values, we will see the second one
	// return window.myVariable+arg;
	return myVariable+arg;
}

finally we are printing the function.

document.writeln(" Output : "+sumValue(2));
// output will be 3
</script>
Share