Skip to content Skip to sidebar Skip to footer

Updating A Global Variable From A Function

There is a global variable called numbers. Function one calculates a random number and stores it in mynumber variable. var mynumber; function one (){ var mynumber = Math.floor(Ma

Solution 1:

If you declare a variable with var it creates it inside your current scope. If you don't, it'll declare it in the global scope.

var mynumber;

functionone (){
    mynumber = Math.floor(Math.random() * 6) + 1; // affects the global scope
}

You can also specify that you want the global scope even if you define a local variable too:

functionone (){
    var mynumber = 1; // localwindow.mynumber = Math.floor(Math.random() * 6) + 1; // affects the global scope
}

Knowing that the global scope is window you can get pretty tricksy with modifying global variables:

functionone (){
    var mynumber = Math.floor(Math.random() * 6) + 1; // localwindow['mynumber'+mynumber] = mynumber; // sets window.mynumber5 = 5 (or whatever the random ends up as)
}

Solution 2:

What you have:

var mynumber = Math.floor(Math.random() * 6) + 1;

Declares a new local variable and then sets a value. Drop the var and you will update the original.

functionone(){
   mynumber = Math.floor(Math.random() * 6) + 1;
}

Post a Comment for "Updating A Global Variable From A Function"