1

no errors in code but output get undefined

code

var xx = document.getElementById("stars").value;
var day;

switch (xx) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
    day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
}

document.getElementById("demo").innerHTML = "Today is " + day;
<p id="demo"></p>
<input type='hidden' id="stars" value='4'>

I have tried many ways but didn't get any solution please help me thanks in advance

Yousaf
  • 27,861
  • 6
  • 44
  • 69
Munna VMC
  • 35
  • 1
  • 9

2 Answers2

2

Switch statement uses strict equality comparison (===) to compare its expression against each case clause.

.value property returns a string. So value of xx, being a string, doesn't matches any case clause because value in each case clause is a number and strict equality comparison between values of two different types always evaluates to false. As a result, day is never initialized with a value other than its initial value of undefined

Changing the each case clause to a number will solve the problem

case "4":
    day = "Thursday";
    break;
Yousaf
  • 27,861
  • 6
  • 44
  • 69
1

value returns a string, and the values in your case expressions are numbers. One solution would be to use string literals there too:

var xx = document.getElementById("stars").value;
var day;

switch (xx) {
  case '0':
    day = "Sunday";
    break;
  case '1':
    day = "Monday";
    break;
  case '2':
    day = "Tuesday";
    break;
  case '3':
    day = "Wednesday";
    break;
  case '4':
    day = "Thursday";
    break;
  case '5':
    day = "Friday";
    break;
  case '6':
    day = "Saturday";
}

document.getElementById("demo").innerHTML = "Today is " + day;
<p id="demo"></p>
<input type='hidden' id="stars" value='4'>
Mureinik
  • 297,002
  • 52
  • 306
  • 350