Ananya Pramanik
Ananya Pramanik

Reputation: 21

How to get the value from variable in switch statement is javascript

var day = "Sunday";
var x;

switch (day) {
  case 0:
    var x = 5;
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
}

document.getElementById("demo").innerHTML = "Today is " + day + " " + x;
<p id="demo"></p>

I want to get output as Today is Sunday 5

but I am getting the output as Today is Sunday undefined

How can get the value as 5 instead of undefined???

Upvotes: 0

Views: 4206

Answers (3)

jasinth premkumar
jasinth premkumar

Reputation: 1413

it is because of mistake in switch statement you are using number instead of day

like case 0: instead of case "sunday" that is the mistake

var day = "Sunday";
var x;

switch (day) {
  case "Sunday":
    var x = 5;
    day = "Sunday";
    break;
  case "Monday":
    day = "Monday";
    break;
}

document.getElementById("demo").innerHTML = "Today is " + day + " " + x;
<p id="demo"></p>

you can try like this too with numbers

The getDay() method returns the weekday as a number between 0 and 6.

(Sunday=0, Monday=1, Tuesday=2 ..)

This example uses the weekday number to calculate the weekday name:

<p id="demo"></p>

<script>
var day;
var x=0;
switch (new Date().getDay()) {
    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 + x;
</script>

How can get the value as 5 instead of undefined???

variable in javascript will be initialized to undefined .so is out puts undefined because it didn't set to 5 in switch case (fails in condition to assing)

Upvotes: 1

Andy
Andy

Reputation: 63550

You might find it easier to use an object to hold a set of keys/values. You can then check the object using the value held in day.

const days = {
  sunday: 5,
  monday: 2
};

let day = "Sunday";

const demo = document.getElementById('demo');
demo.innerHTML = "Today is " + day + " " + days[day.toLowerCase()];
<p id="demo"></p>

Upvotes: 0

Dheeraj Joshi
Dheeraj Joshi

Reputation: 1582

Answer is pretty simple:

switch (day) {
 case 0:
var x = 5;
day = "Sunday";
break;
case 1:
day = "Monday";
break;
}

In the above code switch(day) you are passing a string "Sunday " and in cases matching it with an int type like case 0,it is not possible so try to pass an int in switch() or use case like case "Sunday":

 switch (day) {
 case "Sunday":
var x = 5;
day = "Sunday";
break;
case "anyday"://use case as you want
day = "anyday";
break;
}

Upvotes: 0

Related Questions