This simple problem gives me an error. Does not get the correct answer. I will be glad if you help.
JavaScript
x
22
22
1
let point = 90;
2
switch (point) {
3
case point >= 51 && point <= 60:
4
console.log('Your price: E');
5
break;
6
case point >= 61 && point <= 70:
7
console.log('Your price: D');
8
break;
9
case point >= 71 && point <= 80:
10
console.log('Your price: C');
11
break;
12
case point >= 81 && point <= 90:
13
console.log('Your price: B');
14
break;
15
case point >= 91 && point <= 100:
16
console.log('Your price: A');
17
break;
18
default:
19
console.log('You did not pass');
20
}
21
22
Output:
You did not pass
Advertisement
Answer
this way
JavaScript
1
20
20
1
let point = 90;
2
switch (true) {
3
case point >= 51 && point <= 60:
4
console.log('Your price: E');
5
break;
6
case point >= 61 && point <= 70:
7
console.log('Your price: D');
8
break;
9
case point >= 71 && point <= 80:
10
console.log('Your price: C');
11
break;
12
case point >= 81 && point <= 90:
13
console.log('Your price: B');
14
break;
15
case point >= 91 && point <= 100:
16
console.log('Your price: A');
17
break;
18
default:
19
console.log('You did not pass');
20
}
can you explain why we write
true
? – Hussein Nadjafli (PO)
The JS switch
only works on strict equality.
JavaScript
1
4
1
switch (A) {
2
case ‘x1’:
3
case ‘x2’:
4
is equivalent to
JavaScript
1
3
1
if (A === ’x1’) {
2
else if (A === ’x2’) {
3
in your code you replace the possible values [’x1’,’x2’,…] with an evaluation like
JavaScript
1
2
1
(point >= 61 && point <= 70)
2
which returns either true
or false
so your code becomes:
JavaScript
1
3
1
if (A === (point >= 51 && point <= 60)) {
2
else if (A === (point >= 61 && point <= 70)) {
3
by replacing the A
by true
you therefore have a comparison between:
JavaScript
1
3
1
if (true === (point >= 51 && point <= 60)) {
2
else if (true === (point >= 61 && point <= 70)) {
3
You can also do:
JavaScript
1
7
1
function codePrice(val)
2
{
3
let code = 'ABCDE'[10 - Math.ceil(val / 10)]
4
return (!!code) ? `Your price: ${code}` :'You did not pass'
5
}
6
7
console.log( codePrice(90) )