Help me understand the logic behind this code

The objective is to write a function that adds “Hello” to every element of an array of names - this is the answer i was given:

function greet(list) {

let result= list.map(n =>"Hello "+ n);

return result;

}
console.log(greet([“David”, “Billy”, “Lisa”, “Jennifer”]));

Can someone please break this down for me and explain why it’s right?
Specifically this part " list.map(n =>"Hello "+ n); " is confusing me

The code you mentioned is using the ES6 array method .map:

let result= list.map(n =>"Hello "+ n);

This method creates a new array based on the elements of the array you apply the method to (list in this case). It takes a callback function as an argument. In this case the callback function is:

n =>"Hello "+ n

This function is an arrow function and has an implicit return since it’s only one line of code and not enclosed in curly-braces (so we don’t need to write return in order to return a value from this function). Basically this function will receive the elements in the array (list) one at a time as .map iterates (loops) through the list array. So in the example n represents the current element of the array being given as an argument to the callback function. Then the callback-function will return ‘Hello’ + n for each element of the array. The returned values will be stored in the array that .map returns and here that array is assigned to the variable called result. The .map method is convenient and you will see it a lot in JS and React and get comfortable with it pretty quickly.

2 Likes