# Set a variable in an if statement

I created a function, that has this if…else if

``````if(Quantity < 10 ) {
Discount = 0;
} else if (Quantity < 20 ) {
Discount = .1;
} else if (Quantity < 30) {
Discount = .2
} else if (Quantity < 40) {
Discount = .3
} else if (Quantity < 50 ) {
Discount = .4;
} else if (Quantity < 60) {
Discount = .5;
} else if (Quantity < 70 ) {
Discount = .6;
} else if (Quantity < 80) {
Discount = .7;
} else if (Quantity < 90 ) {
Discount = .8;
} else if (Quantity < 100) {
Discount = .9;
}
console.log(Discount);
``````

which produces

Why cant the function see either the Quantity or Discount variables?
The Quantity variable is declared outside the function and the Discount variable is declared in it

``````var Quantity = document.getElementById("Quantity").value;

function CalculateTotal() {

}
``````

shouldn’t the function be able to see the variable?

Discount is only defined in the context of the if statement. If you want it defined outside, you’ll need to declare it first.

``````var Discount = 0;
if(Quantity < 10 ) {
:
``````
1 Like

ok, that got rid of the error, but if I put 44 in the quantity field, when I run the function, the console.log thing shows 0 when it should show (shouldn’t it show .4)?
http://fixmysite.us/Web_Programming_With_Javascriipt/Assignment7/

Are you sure the quantity field has the value you expect?

1 Like

Something that might help is that there’s a consistent pattern to the discount, that you can represent as a formula.

I realized that 30 gives 0.2, and 80 gives 0.7
Multiplying the discount by 10 results in 30=>2 and 80=>7
From there, you can add one to the discount and multiply by 10, to get the quantity value.

Reversing all of that lets us get from the quantity to the discount.

discount = (quantity / 10 - 1) / 10

Using parseInt so that we end up with single decimal point values, results in the following discount function:

``````function discount(quantity) {
var amount = parseInt(quantity / 10 - 1, 10) / 10;
if (amount > 0.9) {
amount = 0.9;
}
return amount;
}
``````
1 Like

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