SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    328
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How can I use Logical expressions in a switch/case?

    Hello,
    I'm doing a bit of experimentation and would like a bit of advice if possible please.

    In my switch statement I would like to use the || or operator, it works correctly it I set the case to 31, but if I try 1||31 it doesn't.

    If anyone can shed some light on this I'd appreciate it.

    Code:
            myDate = new Date();
    	myMonth = month[myDate.getMonth()];
    	myDay = myDate.getDate();
    	dayAddon= null;
    	myWeekDay = weekday[myDate.getDay()];
    
    	switch(myDay){
    		case (1 || 31):
    			dayAddon = "st";
    			alert(dayAddon);
    			break
    	}
    Thanks

  2. #2
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    switch (true) {

    }

    Personally, normal if/else is what I would use.

  3. #3
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    328
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the reply, though I don't quite understand.

    Are you telling me to replace "myDay" with "true" ?

    I did consider the normal if/else route, but since my experience with switch cases was limited, I wanted to give it a go as it looked cleaner.

    Also I'm going to have 3 or 4 cases, and as you can imagine this will make the code much more difficult to read using if/else.

    What's the reason that it doesn't work with the code that I've attempted, it seems fairly logical.

  4. #4
    SitePoint Evangelist
    Join Date
    Jul 2007
    Posts
    345
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    (1 || 31) will always return true as 1 is truthy. However, the switch statement will check to see if the variable specified is identical to the case value. As myDay is an integer, it will not match the boolean value true.

    You could try to let the code execution 'fall through' your case blocks.
    Code:
    switch(myDay)
    {
       case 1:
       case 31:
          // do stuff
          break;
       // other cases
    }

  5. #5
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    328
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ah that did the trick, thanks a lot.
    I appreciate the explanation also.

    thanks again


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •