john
john

Reputation: 89

How to declare global variables using JS

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?

Upvotes: 2

Views: 357

Answers (7)

Łukasz Baran
Łukasz Baran

Reputation: 1239

You mean something like this:

   var Foo = {
       Bar: Value
   }

Then you can access to this like that:

Foo.Bar

You can also set values:

Foo.Bar = "fancy value"

Upvotes: 0

SaravananArumugam
SaravananArumugam

Reputation: 3720

Any variable that is defined outside a function or a class is global variable in Javascript.

For example:

<script>
    var itsAGlobalVariable;
    function someMethod() {
        var itsALocalVariable;
    }
</script>

Upvotes: 0

digitalbath
digitalbath

Reputation: 7344

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>

Upvotes: 2

Oleg Vaskevich
Oleg Vaskevich

Reputation: 12672

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.

Upvotes: 0

switz
switz

Reputation: 25188

Declare a variable in a script tag before your other scripts.

<script type="text/javascript">
   var global = "hello world";
</script>

Upvotes: 1

Paul Sonier
Paul Sonier

Reputation: 39480

Declare a variable outside any function. It will be accessible in other scripts.

Upvotes: 2

user578895
user578895

Reputation:

"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 var keyword
  • use window.variable = value

Upvotes: 5

Related Questions