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 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,738 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();