Choy
Choy

Reputation: 2117

How to set result of function as global variable

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);
}

Upvotes: 1

Views: 22580

Answers (3)

Álvaro González
Álvaro González

Reputation: 146460

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);
}

Upvotes: 0

Chibu
Chibu

Reputation: 1353

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);
}

Upvotes: 5

Ben
Ben

Reputation: 867

var color = "";

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

window.onload = function() {
    color = selectColor();
    alert(color);
}

Upvotes: 2

Related Questions