# Trying to build a tip calculator to better grasp functions

Hello,

I’ve been challenged with building a tip calculator to test my knowledge of functions. My function seems to check out fine, however is there a reason I am unable run an array through my function and have is output a mutated array?

``````var base = [48, 124, 268];

function tipAmmount(base) {
if(base <= 50) {
var tip = base * .2;
return tip;
} else if (base > 50 && base <= 200) {
var tip = base * .15;
return tip;
} else {
var tip = base * .1;
return tip;
}
}

console.log(tipAmmount());
``````
``````function tipAmmount(base) {
if(base <= 50) {
var tip = base * .2;
return tip;
} else if (base > 50 && base <= 200) {
var tip = base * .15;
return tip;
} else {
var tip = base * .1;
return tip;
}
}

var tips = [48, 124, 268].map(tipAmmount)

console.log(tips)
``````

MDN - Array Map

2 Likes

Well the function doesn’t know that it’s an array that it has to deal with.

The usual solution here is to use a separate function that deals with the array, and uses the tipAmount function to deal with each value.

``````function tipAmounts(amounts) {
const tips = amounts.map(function (amount) {
return tipAmount(amount);
});
return tips;
}
``````

We can then display them in a results section on the page:

``````const results = document.querySelector("#results");
base.forEach(function (amount, index) {
results.innerHTML += "Base: " + amount.toFixed(2) +
" Tips: " + tips[index].toFixed(2) + "\n";
});
``````

I’ve used toFixed(2) to give results rounded to the nearest cent.
I’ve also renamed your function to tipAmount so that it’s correctly spelled.

You can see all of this in action at the following page: https://jsfiddle.net/d39btr4q/

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