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 Node.js Basics (2014) Building a Command Line Application Perfecting: Getting Multiple Profiles

James Barrett
James Barrett
13,253 Points

"Since the callback for each passes one parameter, so let's see this in action." 3:14 has thrown me off a little

Hi guys,

Can't seem to grasp this code snippet properly, despite what Andrew is saying at 3:14:

var profile = require("./profile.js");
var users = process.argv.slice(2);
users.forEach(profile.get);
  • First line is fine, we are requiring from profile.js.
  • Second line is fine, we are just slicing the argv array at the index where our usernames will be entered

However I am unclear on how the forEach is working? It requires a callback function, which is fine; we call the get function in our profile file. However we have a 'username' argument on that function but we aren't supplying anything in users.forEach(profile.get);

How does the program pass through our username arguments to get(username)? I must be missing something really obvious here, perhaps?

Thanks, James.

1 Answer

Thomas Nilsen
Thomas Nilsen
14,957 Points

You are correct in saying that there is an argument on that function. But you're not calling the function, your passing the function as a callback and allow the forEach function to call the function with the appropriate arguments.

Here is a basic example:

//Our very own (and basic) implementation of forEach
Array.prototype.customForEach = function(callback) {
    for (var i = 0; i < this.length; i++) {

        //Here, we're invoking the function we passed in
        callback(this[i]);
    }
}


//A function that accepts a number and prints it out
function printNumbers(n) {
    console.log(n);
}


//The arrray we're working with
var arr = [1, 2, 3, 4, 5];


//Here we're calling our custom forEach and passing the function to it
//(NOT calling it)
arr.customForEach(printNumbers);