nimala9
nimala9

Reputation: 201

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(Math.random() * 6) + 1;
}

I need to use it in a separate function as belows. But an error says undefined - that means the value from function one is not updated.

function two (){
alert(mynumber);
}

How to overcome this problem. Is there a way to update the mynumber global variable.

Upvotes: 0

Views: 133

Answers (2)

Joe
Joe

Reputation: 15802

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;

function one (){
    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:

function one (){
    var mynumber = 1; // local
    window.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:

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

Upvotes: 3

mostlydev
mostlydev

Reputation: 723

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.

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

Upvotes: 3

Related Questions