1

I am using a switch statement to search for undefined values to manually change it. but I am having trouble using boolean expressions as I would when using an if statement.

Like: if statemant

if(Item1 == undefined)
{
  item1 ="No";
}
else if (Item2 == undefined)
{
  item2 = "No";
}

etc..

I tried this with the switch statement:

 switch (array) {
 case (item1 == undefined):
 item1 = "No";
 console.log('item1 result', item1 );
 break;
 case item2 == undefined:
 item2 = "No";
 console.log('item2 result', item2 );
 break;
 default:

 }

It does not run through the switch statement, except for when I remove == undefined and only use item1. then it works?

1
  • 2
    You need to learn basics. switch
    – Satpal
    Apr 8, 2016 at 7:31

4 Answers 4

2

The switch cannot evaluate values of the array like that and that is why it does not run through the switch statement. You need to define which value of that array you want to switch.

Inside case statement you also cannot use expression, you have to use a value there as well.

So, if you are dead set on using switch for what you are trying to accomplish, you can do something like this:

item1 = array[1];
switch(item1) {
    case "undefined":
        // so on
    break;
}

But, based on your example you are probably trying to check if the values are set or not, for that if statements are still the best choice rather than switch.

$arr = []; // Your array
if(typeof $arr[0] == "undefined") {
    $arr[0] = "No";
}
3
  • I did use if statements previously but was told it is better to do a switch?
    – user2413453
    Apr 8, 2016 at 7:40
  • @RGdent, Why is that? What exactly did he say? And why would switch be better for what you are trying to do?
    – Starx
    Apr 8, 2016 at 7:43
  • there may have been a misunderstanding then, thank you for clearing that up appreciate it!
    – user2413453
    Apr 8, 2016 at 7:46
0

switch can be applied only 1 variable as follows:

switch (array) {
 case 'undefined':
 item1 = "No";
 console.log('item1 result', item1 );
 break;
 case array.length:
 item2 = "No";
 console.log('item2 result', item2 );
 break;

 }
0

Useful when reading arguments of function.

Short and simple approach would be

item1 = (item1 == null)? item1 : 'no';
item2 = (item2 == null)? item2 : 'no';

If item is undefined or null it will assign value otherwise that particular item.

p.s. this is for checking null or undefined and better than using switch

0
for(var i=0;i<array.length;i++){ 
    switch(array[i])  {
    case "undefined":
   //so on
      break;
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy