views:

44

answers:

3

I'm sure this is really simple and I'm drawing a giant blank, but how do you set the result of a function as a global variable?

Example, I want to set the first "color" in array "colors" as global variable "color" (I know the example doesn't make much practical sense, but it's just to illustrate my question):

var color = "";

function selectColor () {
    var colors = ["blue","red","green","yellow"];
    var color = colors[0];
    return color;
}

window.onload = function () {
    selectColor ();
    alert(color);
}
+2  A: 
var color = "";

function selectColor() {
    var colors = ["blue","red","green","yellow"];
    var color = colors[0];
    return color;
}

window.onload = function() {
    color = selectColor();
    alert(color);
}
path411
this method works too, thanks.
George
+2  A: 

It should work for you if you remove the var declaration from color in the selectColor() function, like this:

var color = "";

function selectColor () {
    var colors = ["blue","red","green","yellow"];
    color = colors[0];
    return color;
}

window.onload = function () {
    selectColor ();
    alert(color);
}
Chibu
Added point: JavaScript variable scope is based on functions. If you declare a variable with var inside a function, it is *different* from a global variable of the same name. If you don't declare a variable with var, it is implied to be global, regardless of whether it was declared outside the function or not.
Matt
Yeah, this was my problem, I was confusing the variables because I declared it again inside the function, thanks.
George
In this example you wouldn't need `return color;`, the `selectColor()` function would be simply setting the global variable instead of returning the result.Fine for something simple like this, but if you need to work with the variable before setting it global, I would leave color as a local variable and return the result.
path411
A: 

Answering to your question:

var color = "";

function selectColor () {
    var colors = ["blue","red","green","yellow"];
    color = colors[0];
}

window.onload = function () {
    selectColor ();
    alert(color);
}
  • The var keyword creates a local variable inside selectColor(); you don't want that.
  • The return statement is not necessary; you don't capture it.

In any case, in this exact example it'd be cleaner to do this:

var color = "";

function selectColor () {
    var colors = ["blue","red","green","yellow"];
    return colors[0];
}

window.onload = function () {
    color = selectColor ();
    alert(color);
}
Álvaro G. Vicario