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
S Ananda
9,474 PointsHow does an anonymous function know what function to do?
I'm working in JS and the DOM. We just wrote a function and then turned it into an anonymous function. In the original function we use the function "say" as the first parameter and the argument "Hello" as the second. When we finished with the anonymous function it no longer had the word say in the syntax, so how does the function know to say what is passed as the argument? How would you do this if you changed your mind and wanted it to do a different function? This seems pretty mysterious to me at the moment.
2 Answers
Robin van Loon
10,301 PointsThe function doesn't need a name. When you call the function all the code inside the curly brackets is executed.
The function is probably assigned to a variable and when it's used the function is called and the code gets executed.
The function knows what to do because it just executes the code inside it, like "saying" hello. Printing it to the console or placing it in the HTML on the page.
Alexander Davison
65,469 PointsDon't think that an anonymous functions are reusable. They are used as a regular value is. You pass them into functions like plain old numbers and strings do. They are just for representing blocks of code, and not meant to be reusable.
However, if you give them a name, they can be reusable.
They are so much like plain old values that you can even assign a variable to it and that's the same as defining a function the way you are used to:
var sayHello = function () {
document.write("Hello");
}
// The line above is THE SAME AS the line below
function sayHello () {
document.write("Hello");
}
// The lines above are also THE SAME AS the one below
var sayHello = () => {
document.write("Hello");
}
In fact, You van even create a regular reusable function and pass it in to a DOM function:
var element = document.getElementById("someElement");
function sayHello () {
document.write("Hello");
}
element.addEventListener('mouseover', sayHello);
I hope this helps. ~Alex