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 trialja5on
10,338 PointsPassing a function as an argument.
function sayHello() {
return "Hello, ";
}
function greeting(helloMessage, name) {
console.log(helloMessage() + name);
}
greeting(sayHello, "JavaScript!");
I can tell helloMessage is an arugument but could someone tell me what helloMessage() is please, because its not a function as I can see?
My guess would be that it's a call its itself?? Thats just a wild guess...
1 Answer
Juan Luna Ramirez
9,038 PointsThe value of helloMessage
should be a function because that's how you are using it in greeting
. So in your example, the value of sayHello
, a function, becomes the value of helloMessage
when running greeting(sayHello, "Javacript!")
. So it all works out.
But lets say I did not use a function as the fist argument. Say I did greeting("hello", "Javascript!")
. In this case, helloMessage
becomes "hello"
, a string . This would result in a syntax error because you can't run a string.
In other words, helloMessage
becomes whatever you pass into the function when you run the function.