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
Cory Thomas
4,789 PointsWhat's the point? Functions as a parameter
What's the point of setting up functions as a parameter and why is this discussed in the DOM course???
I can see how it can be done and I understand it but I don't think Guil did a good job explaining on WHY we need to know how to do it and how it's applicable, or just applicable to the understanding of the DOM. He only vaguely says it will help us understand how JavaScript can respond to user events.
Plus this seems randomly placed into the DOM course.
Maybe i'm missing something, any tips or advice would be appreciated, thank you.
1 Answer
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsThe main benefit of passing functions as a parameter in DOM manipulation is passing callback functions to event listeners.
Let's say we want to update the contents of some container when someone clicks a button:
const button = document.querySelector("#button");
const messageContainer = document.querySelector(".message-container");
button.addEventListener("click", function(){
messageContainer.innerHTML = "Button was clicked";
});
The 2nd argument to the method addEventListener is a function. In this case, we're passing in an anonymous function. But we could also assign a function to a variable, and then pass that in.
const button = document.querySelector("#button");
const messageContainer = document.querySelector(".message-container");
const updateMessageContainer = () => {
messageContainer.innerHTML = "Button was clicked";
}
button.addEventListener("click", updateMessageContainer);
Notice that when we pass in the function as an argument, we pass in the name of the function without parens, we're not calling it yet. We're just passing the reference to the function, and later on, when the button is clicked, the function will be called.