FUNCTIONS
Return II
In the last exercise, we pointed out that using
return
makes programs more maintainable and flexible, but how exactly?
When functions
return
their value, we can use them together and inside one another. If our calculator needed to have a Celsius to Fahrenheit operation, we could write it with two functions like so:
const multiplyByNineFifths = (celsius) => {
return celsius * (9/5);
};
const getFahrenheit = (celsius) => {
return multiplyByNineFifths(celsius) + 32;
};
console.log('The temperature is ' + getFahrenheit(15) + '°F');
// Output: The temperature is 59°F
Take a look at the
getFahrenheit()
function. Inside of its block, we called multiplyByNineFifths()
and passed it the degrees in celsius
. The multiplyByNineFifths()
function multiplied the celsius
by (9/5)
. Then it returned its value so the getFahrenheit()
function could continue on to add 32
to it.
Finally, on the last line, we interpolated the function call within a
console.log()
statement. This works because getFahrenheit()
returns its value.
We can use functions to section off small bits of logic or tasks, then use them when we need to. Writing functions can help take large and difficult problems and break them into small and manageable problems.
1.
It's your job to calculate two more numbers for each order:
- A sales tax of 6% needs to be calculated for every full order. This should be based on the subtotal.
- The total, which is the subtotal plus tax, should also be computed.
Let's start with calculating the tax. Under the
getSubTotal()
function, create a function expression using the variable const
named getTax
. This function will take one parameter named itemCount
.
Stuck? Get a hint
2.
Inside the
getTax()
function, call your getSubTotal()
function and pass it the argument itemCount
to get the subtotal, and then multiply the returned value by 6% (0.06
). Make sure to return
the result of this operation.
Stuck? Get a hint
Tidak ada komentar:
Posting Komentar