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 trialjlampstack
23,932 PointsMy understanding of Passing say() function????
I would like to clarify my understanding is correct for this step. The block of code is written on multiple lines so it can be mind boggling at first.
- We are calling exec() and passing it 2 arguments.
- The first argument is a function named say(something)
- The second argument is the string we would like to pass into say(something)
- The arguments then get executed as a function
In otherwords we are passing a function into a function as the first argument, and the second "arg" as a string.
The main function here is....
exec(func, arg);
The first argument for exec() is a function
function say(something) {
console.log(something);
},
The second argument for exec() is where it gets a bit tricky for me. It's a string that gets passed into say(something) ????
'Hi, there'
Which function of the two is 'Hi, there' being being passed to?
- exec(func, arg)
- say(something?
2 Answers
Dane Parchment
Treehouse Moderator 11,077 PointsI believe it is being passed into both!
If you remember correctly JavaScript treats functions like first class citizens (in functional programming this is referred to as a high-order function), this means that functions can be used just like any other data type within JavaScript!
In this case the function exec(func, args);
is simply executing a function with the provided arguments. So if we follow the trail of the exec function then we will see that this is how it works:
exec(func, args);
will probably look like this if we were to fully write it out:
function exec(func, args) {
func(args);
}
This shows us that if we were to use the other function say()
; as the func
parameter and Hi, there
for the args
parameter, then we know that these two parameters are first being used by exec
.
Then exec
calls the func
parameter as a function and places the args
parameter within func
as a parameter for that function.
So in order of execution:
-
Exec
is called -
Exec
takes in both parameters:exec(say, 'Hi there');
-
Exec
calls thesay
function and places'Hi there'
within it as the function dictates:func(args) == say('Hi there')
-
say
will then `console.log('Hi there') -
Exec
has completed it's task!
jlampstack
23,932 PointsIt's much easier to understand when you break it down like this. Thanks for the explanation.