11- 11- - 2 years ago 121
Javascript Question

Simple Practice Function Displays NaN

function basketPrice(product, vat, delivery) {
var total = product + vat + delivery;
delivery = 7.5;
vat = 20/100 * product;

return total
}

basketPrice(150);


So just for the record I started looking into JavaScript about a week back so please excuse any dumb mistakes or lingo.

Above I am trying to generate a very simple output. I'm sure this isn't how you produce a basket on an e-commerce website, but it's just an example I'm using to help me practice.

I thought I had this down until my result was NaN (which I'm aware means Not a Number) but I have no idea which bit it is relating to and why.

I am looking for an explanation (as simple as possible) on where I've gone wrong. Any help is appreciated.

Thank you in advance.

Answer Source
function basketPrice(product, vat, delivery){
    console.log(product,vat,delivery);//150,undefined,undefined

  var total=product + vat + delivery;//150+undefined is not a number

 delivery=7.5;//now its to late to change sth
 vat = 0.2 * product;

 return total;
}

basketPrice(150);

Youre setting the variables after youve calculated total. So may use default values and/or set them before you calculate total:

function basketPrice(product, vat, delivery=7.5){

console.log(product,vat,delivery);//150,undefined,7.5

vat = vat || 0.2 * product;

 var total=product + vat + delivery;// is a number

 return total;
}
basketPrice(150);
basketPrice(1,2);
basketPrice(1,2,3);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download