I just learned switch statements. I was practicing it by building something. When i set the value of variable to a number it works but when i asks the user for a number it always outputs the default statement.
It works with this code:
JavaScript
x
42
42
1
confirm("You want to learn basic counting?");
2
var i = 0;
3
switch (i) {
4
case 0:
5
console.log(i);
6
i++
7
case 1:
8
console.log(i);
9
i++;
10
case 2:
11
console.log(i);
12
i++;
13
case 3:
14
console.log(i);
15
i++;
16
case 4:
17
console.log(i);
18
i++;
19
case 5:
20
console.log(i);
21
i++;
22
case 6:
23
console.log(i);
24
i++;
25
case 7:
26
console.log(i);
27
i++;
28
case 8:
29
console.log(i);
30
i++;
31
case 9:
32
console.log(i);
33
i++;
34
case 10:
35
console.log(i);
36
console.log("Congratulations!");
37
break;
38
default:
39
console.log("Buzz, wronghh");
40
break;
41
}
42
But when i asks value from user, it dosen’t work. Code below doesn’t work:
JavaScript
1
42
42
1
confirm("You want to learn basic counting?");
2
var i = prompt("Type any number from where you want to start counting[Between 0 and 10]");
3
switch (i) {
4
case 0:
5
console.log(i);
6
i++
7
case 1:
8
console.log(i);
9
i++;
10
case 2:
11
console.log(i);
12
i++;
13
case 3:
14
console.log(i);
15
i++;
16
case 4:
17
console.log(i);
18
i++;
19
case 5:
20
console.log(i);
21
i++;
22
case 6:
23
console.log(i);
24
i++;
25
case 7:
26
console.log(i);
27
i++;
28
case 8:
29
console.log(i);
30
i++;
31
case 9:
32
console.log(i);
33
i++;
34
case 10:
35
console.log(i);
36
console.log("Congratulations!");
37
break;
38
default:
39
console.log("Buzz, wronghh");
40
break;
41
}
42
Advertisement
Answer
You need to convert the user input from a string to an integer, like so
JavaScript
1
6
1
confirm("You want to learn basic counting?");
2
var i = prompt("Type any number from where you want to start counting[Between 0 and 10]");
3
i = parseInt(i); // this makes it an integer
4
switch(i) {
5
//...
6