Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

jason chan
jason chan
31,009 Points

javascript self invoking function

function adventureSelector(userChoice){
  if (userChoice == 1) {
    return function() {
      alert("You selected the Vines of Doom!");
    };
  } else if (userChoice == 2) {
    return function() {
      alert("Looks like you want the Lake of Despair!");
    };
  } else {
    return function() {
      alert("The Caves of Catastrophe!");
    };
  }
}
// choice one
adventureSelector(1)();
// choice two
adventureSelector(2)();
// everything else
adventureSelector()();

vs

// to call a function
var ad = adventureSelector(1);
ad();

so basically all you do is add () at the end of the function to create the self invoking function. Pretty cool you do not have to define a variable.

Won't that just run through the 3 functions at the end? I mean, won't that just print the following:

You selected the Vines of Doom!
Looks like you want the Lake of Despair!
The Caves of Catastrophe!

Confused!

I use this to wrap my code in an anonymous function to silence the lint checker (it annoys me otherwise haha):

(function () {
  'use strict';
  //code
}());

1 Answer

jason chan
jason chan
31,009 Points

Yup.

I'm just checking if all three functions work and they do.

Ah ok! Thought there was more to it! :)