JavaScript Node.js Basics Handling Errors in Node Organizing Your Code with require

Jesse Thompson
Jesse Thompson
10,682 Points

Little confused with how users.forEach(profile.get); grabs users for get function

So my app functions perfectly but I am confused as to how some of the syntax works.

In my app.js file I have the following


const profile = require('./profile.js');

// process is a native object that takes command line words to be passed as arguments after node whateverapp.js is written. // this is put into a variable and a forEach function loop is ran to run the getProfile function with each user passed as the argument for username. const users = process.argv.slice(2); users.forEach(profile.get); ` and in the profile.js I have pretty much exactly what Andrew has in his file.

For the last line in the app file. The users variable is passed as an argument to the get function? The syntax here is so weird its hard for me to make out. Im expecting something like profile.get(users));

1 Answer

james south
james south
Front End Web Development Techdegree Graduate 33,244 Points

users is not in parens anywhere so it is not itself being passed as an argument. what is happening here is what is described in the comments - process.argv is an array and you are calling the native JS array method slice on it to get all but the first 2 items, which are the profile names entered when you run the app from the command line. these names are in an array assigned to the users variable. then, the native array method forEach is called on the users array, and for each name in the users array, profile.get is called.