Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Basics (Retired) Creating Reusable Code with Functions Introducing Functions

Jesse Dispoto
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jesse Dispoto
Front End Web Development Techdegree Graduate 14,538 Points

Can anonymous functions only be used once in a given piece of code?

From my understanding of anonymous functions, they are not called and the function is declared at runtime and stored in a variable. So, once the program is ran, we have the variable passed through a function. Instead of a regular function, which can be used anywhere you want in your code and can be called over and over again. Is my understanding correct?

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,696 Points

The anonymous function is called, it just gets called later. The code that calls the function might not be visible to you, it might be buried in the source code for a library that you're using. But you can also right code yourself that takes in an anonymous function and then calls it later.

function doSomethingAfterOneSecond(callback) {
  setTimeout(function(){
    callback(); // This is when it gets called
  }, 1000);
}

doSomethingAfterOneSecond(function() {
  console.log("Hello Future-World");
})

In this case, the anonymous function is assigned to the callback parameter. Inside my function doSomethingAfterOneSeconds, I'm only calling it once, but I could have used it bunch of places and called it many times.

Also, in the example in the video at 6:30, this is an anonymous function that gets assigned to a variable. So it starts anonymous but it ends up having a name after all:

var alertRandom = function() {
  var randomNumber = Math.floor(Math.random() * 6 ) + 1;
  alert(randomNumber);
}

alertRandom();