0

My code:

var host_choice = function(){
    var choice;
    do {
        choice = shuffled_list[random_choice()];
    } while (choice == "car" || choice == player_choice);

    return choice;  
};

Here host_choice is a function which I would have to call. But I am unsure how to make it a variable containing choice. I know I am missing something basic here, but how to do it?

Side note: my shuffled_list contains 3 elements. And I want my host_choice variable to contain neither the element car nor the player_choice is there a "fancier" way of doing this?

Felix Rosén
  • 1,391
  • 1
  • 17
  • 33

2 Answers2

2

You can invoke it directly.

var host_choice = (function(){
  var choice;
  do {
      choice = shuffled_list[random_choice()];
  } while (choice == "car" || choice == player_choice);

  return choice;  
})();

This is an example of IIFE (Immediately Invoked Function Expression). It is very handy for various reasons, such as modularity in Javascript.

Val Berthe
  • 1,280
  • 1
  • 13
  • 30
1

You'd call it, with () after it:

var host_choice = function(){
    var choice;
    do {
        choice = shuffled_list[random_choice()];
    } while (choice == "car" || choice == player_choice);

    return choice;  
}(); // <====

Note that that means it will only ever be run once, since you don't keep a reference to the function anywhere.

You'll frequently see this written with () around the function part, too:

var host_choice = (function(){
    var choice;
    do {
        choice = shuffled_list[random_choice()];
    } while (choice == "car" || choice == player_choice);

    return choice;  
})(); // <====

In your case, that's completely a matter of style, you don't need them. If you weren't using the return value, though, you'd need them so the parser didn't think the function keyword was starting a function declaration. (Which is where style comes in: Some people prefer to always include them even when they aren't strictly necessary, since they're necessary sometimes.) Details on that bit in my answer here.

Community
  • 1
  • 1
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639