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 and the DOM (Retiring) Responding to User Interaction Functions as Parameters

Shay Paustovsky
Shay Paustovsky
969 Points

Callback functions and nested functions clarification

Hello,

So I am a bit confused with the idea of passing a function as an argument to another function.

I have this code example and would love if someone could clarify it a bit for me :

function exec(func, arg) {
  func(arg);
}

exec((something) => {
  console.log(something);},
 "Hi, There");

My Question is :

Why does the function output the string "Hi, There" , but the anonymous function requires a parameter named "something" how does it work together?.

Thanks a lot in advance.

Shay

3 Answers

Steven Parker
Steven Parker
210,474 Points

This example is a bit of a mind-bender. But the basic idea is that "Hi, There" gets substituted for "something" when the anonymous function is called.

Since all the anonymous function does is to call "console.log", you could simplify the call to this, which might be a bit less confusing:

exec(console.log, "Hi, There");

yep that is a bit confusing ,

Shay Paustovsky
Shay Paustovsky
969 Points

You're the best Steven,

thanks alot

Shay