4

I can't figure why b arguments greater than 20 don't work here. See results

Exercise: Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10, the surcharge is 1. For each amount greater than 10 and less than or equal to 20, the surcharge is 2. For each amount greater than 20, the surcharge is 3.

Example: addWithSurcharge(10, 30) should return 44.

function addWithSurcharge(a,b) {
let sur1 = 0
if (a <= 10) {
sur1 = 1;
} else if (10 < a <= 20) {
sur1 = 2;
} else if (a > 20) {
sur1 = 3;
}

let sur2 = 0
if (b <= 10) {
sur2 = 1;
} else if (10 < b <= 20) {
sur2 = 2;
} else if (b > 20) {
sur2 = 3; 
}

return a + b + sur1 + sur2;
}

results

clinzy25
  • 91
  • 8

1 Answers1

4

Issue

The reason is that you condition else if (10 < a <= 20) evaluates to true.

  1. 10 < a will be evaluated to true
  2. true <= 20 will be evaluated to true.

So the number will evaluated as boolean and every number greater than 0 evaluates to true. That's the reason why true <= 20 evaluates to true

You can check this by this snippet

console.log(true <= 20)
console.log(true <= 0)
console.log(true <= -3)

Solution

To define a range you should use the && operator like this

 else if (10 < b && b <= 20) 

Then it will

  1. check if 10 < 30 evaluate to true
  2. check if 30 <= 20 evaluate to false
  3. true && false will evaluate to false

function addWithSurcharge(a,b) {
let sur1 = 0
if (a <= 10) {
sur1 = 1;
} else if (10 < a && a <= 20) {
sur1 = 2;
} else if (a > 20) {
sur1 = 3;
}

let sur2 = 0
if (b <= 10) {
sur2 = 1;
} else if (10 < b && b <= 20) {
sur2 = 2;
} else if (b > 20) {
sur2 = 3; 
}

return a + b + sur1 + sur2;
}

console.log(addWithSurcharge(10,30))
Aalexander
  • 4,987
  • 3
  • 11
  • 34