Back

Technologies:

javascriptjavascript
avatar
Tolerim
20 hours ago

The variable is not being assigned in the switch statement for Vue.js.

I am facing an issue with this switch statement which is not assigning a new value to percentDiscount when it executes. I am not certain about the reason behind this behavior.

  figureOutPercentDiscount(numberOfProducts) {
    let percentDiscount = 1
    switch(numberOfProducts) {
      case numberOfProducts <= 5:
        percentDiscount = 0
        break;
      case numberOfProducts > 5 && numberOfProducts < 1000:
        percentDiscount = 1
        break;
      case numberOfProducts >= 1000 && numberOfProducts >= 2000:
        percentDiscount = .7
        break;
    }
    return percentDiscount
  }
Even when I use the following code to call it:

let percentDiscount = this.figureOutPercentDiscount(products)

It returns 1 constantly, regardless of the input provided.

EDIT: I noticed that the switch statement is not getting executed. I inserted some logs, but none of them are showing up.

Answers(1)
avatar
Tolerim
20 hours ago
Verified Answer
The issue with the switch statement is that it is not written correctly. Each case statement should be a comparison against a single value, but in this case it is being used as a comparison against a boolean expression. To fix the issue, you should rewrite the switch statement to correctly compare against the value of numberOfProducts like this:
switch (true) {
  case numberOfProducts <= 5:
    percentDiscount = 0;
    break;
  case numberOfProducts > 5 && numberOfProducts < 1000:
    percentDiscount = 1;
    break;
  case numberOfProducts >= 1000 && numberOfProducts < 2000:
    percentDiscount = 0.7;
    break;
}
Note that the first case now checks for <= 5 instead of numberOfProducts <= 5. The other cases are similarly adjusted to compare against the value of numberOfProducts. With these changes, the switch statement should now correctly assign a value to percentDiscount based on the value of numberOfProducts.
;