How to declare a global variable using JavaScript, whose life remain through out the HTML code? Can we access the variable that we had declared in one script in another script?
7 Answers
"Don't do this" is the simple answer. Clogging the global scope is generally a bad thing, especially if you have to ask how (which usually means that you're asking because you think it's the easy solution, but it's almost certainly not the right one). What exactly are you trying to do?
If you really want to, either:
- declare it outside of any function
- don't use the
varkeyword - use
window.variable = value
4 Comments
Global variables are declared by using either the var keyword outside of the scope of a function, by assigning a variable without using var, or by directly assigning a property of the window object.
<script>
var global1 = 'foo';
global2 = 'bar';
window.global3 = 'baz';
function f() {
var not_global;
}
</script>
1 Comment
var as a means of creating a global. You'll get a ReferenceError if you're running your code in strict mode.Declare your variable in a <script> tag, but make sure to place it within your <body> tag, or the browser may not execute it!
Alternatively you may use a cookie.
window.variable = 'value'?-1that if I could.window.is valid,top.isn't as it can potentially go to a different frame.top., it's only safely accessible usingtop., which is just a bad style in my opinion.windowandtopandself?