Hi everybody, can anyone clear up this basic thing for me please? I know this sounds like an elementary question but I don’t want to leave this unclarified in case it will come back to bite me in more advanced situations.
Below you will see two almost Identical snippets of code, the first one is the correct answer for the task at hand, the other one is almost exactly the same but omits the line const teaCup = prepareTea(); and pushes prepareTea instead. As a result, the first one gives the correct answer, which is greenTea printed 40 times, the other one prints prepareTea 40 times. Why should we assign prepareTea to a local variable within a function in order to operate correctly?
/**
* A long process to prepare tea.
* @return {string} A cup of tea.
**/
const prepareTea = () => 'greenTea';
/**
* Get given number of cups of tea.
* @param {number} numOfCups Number of required cups of tea.
* @return {Array<string>} Given amount of tea cups.
**/
const getTea = (numOfCups) => {
const teaCups = [];
for(let cups = 1; cups <= numOfCups; cups += 1) {
const teaCup = prepareTea();
teaCups.push(teaCup);
}
return teaCups;
};
// Add your code below this line
const tea4TeamFCC = getTea(40); // :(
// Add your code above this line
console.log(tea4TeamFCC);
/**
* A long process to prepare tea.
* @return {string} A cup of tea.
**/
const prepareTea = () => 'greenTea';
/**
* Get given number of cups of tea.
* @param {number} numOfCups Number of required cups of tea.
* @return {Array<string>} Given amount of tea cups.
**/
const getTea = (numOfCups) => {
const teaCups = [];
for(let cups = 1; cups <= numOfCups; cups += 1) {
teaCups.push(prepareTea);
}
return teaCups;
};
// Add your code below this line
const tea4TeamFCC = getTea(40); // :(
// Add your code above this line
console.log(tea4TeamFCC);
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/learn-about-functional-programming