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

JavaScript

Call Back Confusion

In the first function, callback(name); confuses me. So does this mean the "name" value is only returned when its used in a function? Also how does getUserName(greeting); work exaclty?

function getUserName(callback) { const name = prompt('What is your name?'); callback(name); }

function greeting(name) { alert('Hello, ' + name); }

getUserName(greeting); // a reference to the greeting function is passed to the function

1 Answer

Steven Parker
Steven Parker
231,172 Points

The "callback" is provided as an argument, and "name" is input from the console (by "prompt"). So the code "callback(name)" invokes the function that was passed in, and passes "name" as an argument to it. If that all seems a bit complicated, it really is! But it illustrates a powerful feature of JavaScript that is good to know how to use.

The "name" value is used by the callback function (which is "greeting" in the example), but it is not returned by either function.

Gotcha, it' slowly starting to click but I'm getting there thank you!