Skip to content
Advertisement

Switch…case in JS

This simple problem gives me an error. Does not get the correct answer. I will be glad if you help.

let point = 90;
switch (point) {
    case point >= 51 && point <= 60:
        console.log('Your price: E');
        break;
    case point >= 61 && point <= 70:
        console.log('Your price: D');
        break;
    case point >= 71 && point <= 80:
        console.log('Your price: C');
        break;
    case point >= 81 && point <= 90:
        console.log('Your price: B');
        break;
    case point >= 91 && point <= 100:
        console.log('Your price: A');
        break;
    default:
        console.log('You did not pass');
}

Output: You did not pass

Advertisement

Answer

this way

let point = 90;
switch (true) {
    case point >= 51 && point <= 60:
        console.log('Your price: E');
        break;
    case point >= 61 && point <= 70:
        console.log('Your price: D');
        break;
    case point >= 71 && point <= 80:
        console.log('Your price: C');
        break;
    case point >= 81 && point <= 90:
        console.log('Your price: B');
        break;
    case point >= 91 && point <= 100:
        console.log('Your price: A');
        break;
    default:
        console.log('You did not pass');
}

can you explain why we write true? – Hussein Nadjafli (PO)

The JS switch only works on strict equality.

switch (A) {
   case ‘x1’: ...
   case ‘x2’: ...

is equivalent to

if       (A === ’x1’) { ...
else if  (A === ’x2’) { ...

in your code you replace the possible values [’x1’,’x2’,…] with an evaluation like

(point >= 61 && point <= 70)

which returns either true or false
so your code becomes:

if       (A === (point >= 51 && point <= 60)) { ...
else if  (A === (point >= 61 && point <= 70)) { ...

by replacing the A by true you therefore have a comparison between:

if       (true === (point >= 51 && point <= 60)) { ...
else if  (true === (point >= 61 && point <= 70)) { ...

You can also do:

function codePrice(val)
  {
  let code = 'ABCDE'[10 - Math.ceil(val / 10)]
  return (!!code) ? `Your price: ${code}` :'You did not pass'
  }

console.log( codePrice(90) )
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement