javascript switch matching rules?

Status
Not open for further replies.
Two quick questions:

First, what's a nice online javascript reference? I'm very new to JS (ie: moving from fixing things to writing things) and I keep googling for things as I need them and up at a bunch of crappy w3schools type sites. Something similar to (god help me) the php reference perhaps.

Second, what are the rules regarding the match inside a switch statement?

I had this little snippet really confusing me for a bit. The typo is obvious, I was yanking/putting in vim and missed the "break":

Code:
            switch(fieldName) {
                case "email":
                if(!emailReg.test(inputVal) || inputVal == '' ){
                    $(this).addClass('errorbkg-email');
                        $parentTag.append('<span class="error" id="error" style=
"display:none;">email</span>');
                // there should be a break; here
                }
                case "email-nobkg":
                if(!emailReg.test(inputVal) || inputVal == '' ){
                    $(this).addClass('errorbkg');
                        $parentTag.append('<span class="error" id="error" style=
"display:none;">email nobkg</span>');
                }
                break;
[and so on, a few more matches]

The way this behaved is an input field named "email" ended up hitting both of those "case" statements and it had both classes added. I know I should have the "break;" at the end of each matching block, but I don't follow why the switch statement executed the "email-nobkg" match. Any clues? I was looking for more detailed info on what kind of matching one can do in the "case" block, but came up with very little. For all I know putting a match in double-quotes makes it a really loose match or something. :)
 

technophile

Ars Legatus Legionis
23,768
Because if you don't have a break;, it doesn't break. It just keeps going. It has nothing to do with matching (it does an exact match on the value), just the way switches work.

Also, the breaks should be outside the conditional braces in your example, otherwise you'll get the same behavior if the "if" evaluates to false.

It's intentionally used sometimes, if you have two cases that need to do the same thing, or if you have one case that is a subset of another, so you don't have to duplicate code.

Code:
switch (something) {
  case 'something1':
  case "something2":
    // Will execute for both values something1 and something2
    break;
  case "something3"
    // Will execute for only something3
  case 'something4':
    // Will execute for BOTH something3 and something4, because something3 lacks a break statement
    break;
}
Most of the time it's unintentional and an error, but since sometimes it's valid the compiler (such as it is in JS) can't catch it. I believe tools like JSLint might flag it, but I haven't checked.


Also, for what you're doing here, you may want to investigate jquery and unobtrusive validation; they're much easier to use than manually setting up some kind of validation loop.
 
technophile":6i3yw6m0 said:
Because if you don't have a break;, it doesn't break. It just keeps going. It has nothing to do with matching (it does an exact match on the value), just the way switches work.

Interesting. It looked like that's what it was doing, but I couldn't puzzle out why it would keep going when the match wasn't valid.

technophile":6i3yw6m0 said:
Also, the breaks should be outside the conditional braces in your example, otherwise you'll get the same behavior if the "if" evaluates to false.

I did have it outside, but in my haste to share my awesome mistake I put it in the wrong place here... I assume if it was in the conditional braces it would break on a match with the form field name and a match on the conditional check, but not on just the form name check, which would probably lead to some really fun debugging.

technophile":6i3yw6m0 said:
It's intentionally used sometimes, if you have two cases that need to do the same thing, or if you have one case that is a subset of another, so you don't have to duplicate code.

Code:
switch (something) {
  case 'something1':
  case "something2":
    // Will execute for both values something1 and something2
    break;
  case "something3"
    // Will execute for only something3
  case 'something4':
    // Will execute for BOTH something3 and something4, because something3 lacks a break statement
    break;
}
Most of the time it's unintentional and an error, but since sometimes it's valid the compiler (such as it is in JS) can't catch it. I believe tools like JSLint might flag it, but I haven't checked.

Neat stuff, but I assume I should avoid that.
technophile":6i3yw6m0 said:
Also, for what you're doing here, you may want to investigate jquery and unobtrusive validation; they're much easier to use than manually setting up some kind of validation loop.

I am using some jquery (.addClass, .append and some other stuff outside of this sample). What provided me some motivation to back up and try to learn the basics was actually looking through the jquery api and seeing how incredibly useful it is. I also picked up some of the JS syntax that formerly baffled me in looking through the examples on the jquery site. I'm really long overdue on learning at least the basics. I had a few a-ha moments this past week where it really hit me just how amazing it is to be able to manipulate html elements from JS. I'm a little late to the party...

I just did the first two chunks of the JS class at codecademy the other night and I'm actually finding I kind of like javascript and it does feel like a nice language for figuring out what I guess is "object oriented" programming. Obviously I don't do this for a living, but I do have many years of shell scripting under my belt, but everything I do with that is very linear and not terribly "smart" as far as reusing stuff. I mean, I'll make a function after I realize I've done the same thing three times, but I'd like to expand my horizons a bit. I work with perl sometimes for sysadmin tasks, especially if I need to interact with a database, php more than I'd like to admit, and can follow/fix really basic C. But really I'd like to stop my current method of finding some crappy php script somewhere, spending hours fixing up bad things in it, and then wondering if I shouldn't have just started from scratch. I sensed I was going to start down that road with javascript, so here I am (and yes, the above snippet started as someone else's validation code).

Debugging javascript though, not really liking that.

Thanks for the help, truly appreciated.
 
npHardProblem":23yn8vym said:
My go-to for online js reference is MDN: https://developer.mozilla.org/en/JavaScript

I think the organization could be better, but its accuracy is pretty good and you won't be distracted with a million banner ads for fly-by-night web hosting services.

Thanks. Certainly better than anything else I stumbled upon.

Here's my buddy switch: https://developer.mozilla.org/en/JavaSc ... nts/switch

They don't mention this usage though, which looked really clever, but perhaps isn't universally supported:

Code:
function test(str) {
    switch (true) {
      case /xyz/.test(str):
        display("• Matched 'xyz' test");
        break;
      case /test/.test(str):
        display("• Matched 'test' test");
        break;
      case /ing/.test(str):
        display("• Matched 'ing' test");
        break;
      default:
        display("• Didn't match any test");
        break;
    }
}

Found here: http://stackoverflow.com/questions/2896 ... javascript
 

technophile

Ars Legatus Legionis
23,768
^^^^ That's interesting, I didn't know you could use non-constant expressions in a switch. Most languages only allow constant values.

sporkme":s3a9e227 said:
technophile":s3a9e227 said:
Because if you don't have a break;, it doesn't break. It just keeps going. It has nothing to do with matching (it does an exact match on the value), just the way switches work.

Interesting. It looked like that's what it was doing, but I couldn't puzzle out why it would keep going when the match wasn't valid.
The syntax originated in C*, and understanding how it originally worked is fairly key. Essentially, all it is is a GOTO statement and several labels. It looks inside the switch for the first match for the value, then runs from that point. If it hits a break, it leaves the switch; otherwise it just keeps going, even if that means dropping into another case.

Neat stuff, but I assume I should avoid that.
Not necessarily; like I said,
technophile":s3a9e227 said:
It's intentionally used sometimes, if you have two cases that need to do the same thing, or if you have one case that is a subset of another, so you don't have to duplicate code.
But in that case it's usually a good idea to insert comments making it explicit that it's supposed to fall through and isn't a missing break.

Debugging javascript though, not really liking that.
Use Chrome -- it has the best (and most frequently updated) set of debugging tools of any browser at the moment. It also has a number of semi-hidden features that are really nice; I think Paul Irish has a number of posts on them if you search.


* Well, AFAIK. It may have been in B or something, I'm not sure. :)
 
technophile":3gw3pweh said:
The syntax originated in C*, and understanding how it originally worked is fairly key. Essentially, all it is is a GOTO statement and several labels. It looks inside the switch for the first match for the value, then runs from that point. If it hits a break, it leaves the switch; otherwise it just keeps going, even if that means dropping into another case.
Yes, and in hindsight everyone realizes that this behavior is shit - seasoned programmers insert "break"s by default and remove them as an exception, along with comments indicating that the lack of a "break" is actually intentional and not a bug. There are times when you retain backward compatibility and times when you abandon it. When designing a completely new language with profound differences from C, it's silly to retain C's idiosyncrasies.
 
Status
Not open for further replies.