Javascript curriculum - Functions = Return - question about code in the example and itemCount vs. orderCount in the exercise


#1

‘’’
const getAverage = (numberOne, numberTwo) => {
const average = (numberOne + numberTwo) / 2;
return average;
}

console.log(getAverage(365, 27));
// Output: 196
‘’’

Why in this example code did we create a second constant variable called average, instead of using const getAverage?

Would the code work the same way, if I wrote?

‘’’
const getAverage = (numberOne, numberTwo) => {
const getAverage = (numberOne + numberTwo) / 2;
return getAverage;
}

console.log(getAverage(365, 27));
// Output: 196
‘’’

My other question is about itemCount in the exercise code. I’ve checked out this discussion forum for some older discussions related to it, but I still don’t understand. How does a program know what is an itemCount and how does it give it it’s value since it’s not previously defined? Why have we not used orderCount, since it is defined?

‘’’
let orderCount = 0;

const takeOrder = (topping, crustType) => {
orderCount++;
console.log('Order: ’ + crustType + ’ pizza topped with ’ + topping);
};

takeOrder(‘mushroom’, ‘thin crust’);
takeOrder(‘spinach’, ‘whole wheat’);
takeOrder(‘pepperoni’, ‘brooklyn style’);

const getSubTotal = (itemCount) => {
return itemCount * 7.5;
};

console.log(getSubTotal(orderCount));
"
Is it the last line of code that defines the relationship of itemCount and orderCount? Basically, orderCount translates as a numerical value, which is used in undefined parameter itemCount to calculate the getSubtotal?


#2

it would work, but now you have two variables with the same name, besides getAverage for function name and average for variable name or more accurate in the description of what they do

function parameters (itemCount in this case) are defined when we define the function, they become local variable in the function and get there value from argument at function call, so here:

console.log(getSubTotal(orderCount));

the argument orderCount at getSubTotal function call gets passed to getSubTotal parameter (itemCount)

updating global variable within a function is not a good idea, its bad practice, i do not agree with the design of this whole program. But that was not your question :wink:


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.