Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch/case always returns default value

Tags:

javascript

I have the following problem: my function always returns the default value, no matter what I try. When I use if/else statements everything works fine. Where is the failure?

function auswertung(stueckzahl) {

	var preis1 = 0.77;
	var preis2 = 0.76;
	var preis3 = 0.73;
	var preis4 = 0.69;
	var preis5 = 0.67;

		switch(stueckzahl) {
			
		case ((stueckzahl>=500) && (stueckzahl <= 1000)): {
			return preis1;
		}
		case ((stueckzahl >= 1001) && (stueckzahl <= 2500)): {
			return preis2;
		}
		case ((stueckzahl >= 2501) && (stueckzahl <= 5000)): {
			return preis3;
		}
		case ((stueckzahl >= 5001) && (stueckzahl <= 10000)): {
			return preis4;
		}
		case ((stueckzahl >= 10001) && (stueckzahl <= 30000)): {
			return preis5;
		}
		default: {
			return preis1;
		}

		}
	}
		
document.write (auswertung(10000));
like image 568
Peter Avatar asked Oct 16 '25 04:10

Peter


2 Answers

You can perfectly use a switch with a boolean true as expression to re-evaluate your cases one by one.

This way your code stays clean:

function auswertung(stueckzahl) {
  switch (true) {
    case stueckzahl >= 10001 && stueckzahl <= 30000:
      return 0.67;
    case stueckzahl >= 5001 && stueckzahl <= 10000:
      return 0.69;
    case stueckzahl >= 2501 && stueckzahl <= 5000:
      return 0.73;
    case stueckzahl >= 1001 && stueckzahl <= 2500:
      return 0.76;
    case stueckzahl >= 500 && stueckzahl <= 1000:
    default:
      return 0.77;
  }
}

console.log('500:', auswertung(500));
console.log('10000:', auswertung(10000));
console.log('30000:', auswertung(30000));
like image 184
Yosvel Quintero Arguelles Avatar answered Oct 17 '25 16:10

Yosvel Quintero Arguelles


If you are passing an expression to the case statement then it is evaluated first.

As per spec

  1. Let exprRef be the result of evaluating Expression.

  2. Let switchValue be GetValue(exprRef).

So,

(stueckzahl>=500) && (stueckzahl <= 1000)

will be either true or false.

Which means unless stueckzahl is true/false, it will always go to default section.

You need to replace this switch statements with if/else by doing. (also just check the upper limit in every condition)

    if ( stueckzahl <= 1000) {
        return preis1;
    }
    if ( stueckzahl <= 2500 ) {
        return preis2;
    }
    if ( stueckzahl <= 5000 ) {
        return preis3;
    }
    if ( stueckzahl <= 10000 ) {
        return preis4;
    }
    if ( stueckzahl <= 30000 ) {
        return preis5;
    }
    else {
        return preis1;
    }
like image 38
gurvinder372 Avatar answered Oct 17 '25 16:10

gurvinder372



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!