Switch as a Select Case

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Robert Scheer

    #1

    Switch as a Select Case

    Hi.

    In VBScript I can use a Select Case statement like that:

    Select Case X
    Case 1 to 10 'X is between 1 and 10

    Case 11,14,16 'X is 11 or 14 or 16
    End Select

    Is it possible to use the switch statement in Javascript to do that?
    Do I have to use an if?

    Thanks,
    Robert Scheer
  • McKirahan

    #2
    Re: Switch as a Select Case

    "Robert Scheer" <rbscheer@my-deja.com> wrote in message
    news:cfd22ab6.0 401060558.3f88c 416@posting.goo gle.com...[color=blue]
    > Hi.
    >
    > In VBScript I can use a Select Case statement like that:
    >
    > Select Case X
    > Case 1 to 10 'X is between 1 and 10
    >
    > Case 11,14,16 'X is 11 or 14 or 16
    > End Select
    >
    > Is it possible to use the switch statement in Javascript to do that?
    > Do I have to use an if?
    >
    > Thanks,
    > Robert Scheer[/color]

    Yes; "switch" is to JS as "select" is to VBS.
    To exit a "case", add "break".


    Description

    Enables the execution of one or more statements when a specified
    expression's value matches a label.

    Syntax

    switch (expression) {
    case label :
    statementlist
    case label :
    statementlist
    ...
    default :
    statementlist
    }


    Comment

    • Christopher Jeris

      #3
      Re: Switch as a Select Case

      rbscheer@my-deja.com (Robert Scheer) writes:[color=blue]
      > In VBScript I can use a Select Case statement like that:
      > Select Case X
      > Case 1 to 10 'X is between 1 and 10
      > Case 11,14,16 'X is 11 or 14 or 16
      > End Select[/color]

      JavaScript's syntax is based on that of C, and as in C,
      there is no syntactic sugar for switch statements. However,
      as in C, omitting the "break;" after a switch case will cause
      execution to fall through to the following case. (Opinion is
      divided on whether this is a good thing.)

      switch (x) {
      case 1:
      case 2:
      case 3:
      /* ... */
      case 10:
      // execute some code for this case
      break;

      case 11:
      case 14:
      case 16:
      // execute some other code for this thing
      break;

      default:
      // complain
      break; // for uniformity
      }

      In my opinion it is good practice to mark with LOUD COMMENTS
      places where you use this "fall-through" feature -- except for
      code like the example above, where it's fairly obvious from the
      long string of "case n:" without any intervening code.

      switch (x) {
      case 1:
      // some stuff that has to happen in case 1
      /* *** FALL THROUGH *** */
      case 2:
      // some stuff that has to happen either for 1 or 2
      break;
      }

      In a case such as the VB example you gave above, a chained if-else
      might in fact be clearer and less verbose:

      if (1 <= x && x <= 10) {
      // do some stuff
      } else if (x == 11 || x == 14 || x == 16) {
      // do some other stuff
      } else {
      // complain
      }

      --
      Chris Jeris cjeris@oinvzer. net Apply (1 6 2 4)(3 7) to domain to reply.

      Comment

      • rh

        #4
        Re: Switch as a Select Case

        Christopher Jeris <cjeris@oinvzer .net> wrote in message news:<uk745nlnw .fsf@oinvzer.ne t>...[color=blue]
        > rbscheer@my-deja.com (Robert Scheer) writes:[color=green]
        > > In VBScript I can use a Select Case statement like that:
        > > Select Case X
        > > Case 1 to 10 'X is between 1 and 10
        > > Case 11,14,16 'X is 11 or 14 or 16
        > > End Select[/color]
        >[/color]

        <...>
        [color=blue]
        > In a case such as the VB example you gave above, a chained if-else
        > might in fact be clearer and less verbose:
        >
        > if (1 <= x && x <= 10) {
        > // do some stuff
        > } else if (x == 11 || x == 14 || x == 16) {
        > // do some other stuff
        > } else {
        > // complain
        > }[/color]

        Alternatively, if circumstance or preference implores a switch/case structure:

        switch (x) {
        case ( ( 1 <= x && x <= 10 ) ? x : x+1 ):
        alert("case 1-10: " + x);
        break;

        case (11):
        case (14):
        case (16):
        alert("case 11,14, or 16: " + x);
        break;

        default:
        alert("None of the above: " + x);
        }

        .../rh

        Comment

        • Keith Bowes

          #5
          Re: Switch as a Select Case

          Christopher Jeris wrote:[color=blue]
          >
          > JavaScript's syntax is based on that of C, and as in C,
          > there is no syntactic sugar for switch statements.[/color]

          I disagree. The convenient syntaxes used in BASIC, Pascal, etc. existed
          before C was a language. C was designed to be very low-level, where
          efficiency is paramount; JavaScript is an interpreted language for web
          pages and is well known to be inefficient, and therefore there is no
          reason for stodgily keeping such inconveniences. Furthermore, GCC's
          version of C has the ability for ranges, with a syntax very similar to
          Pascal's.

          Comment

          • Lasse Reichstein Nielsen

            #6
            Re: Switch as a Select Case

            Keith Bowes <do.not@spam.me > writes:
            [color=blue]
            > Christopher Jeris wrote:[color=green]
            >> JavaScript's syntax is based on that of C, and as in C,
            >> there is no syntactic sugar for switch statements.[/color]
            >
            > I disagree.[/color]

            With what? That the syntax is based on that of C (it is, although
            indirectly through the syntax of Java), or that there is no syntactic
            sugar for switch statements (there almost isn't - except that the
            values of a case can be arbitrary expressions)?

            What you seem to be disagreeing with, is that it should be like that
            (and I agree). For a scripting language, the options are too restrictive,
            which is probably why we so rarely see switches.

            /L
            --
            Lasse Reichstein Nielsen - lrn@hotpop.com
            DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
            'Faith without judgement merely degrades the spirit divine.'

            Comment

            • Christopher Jeris

              #7
              Re: Switch as a Select Case

              codeHanger@yaho o.ca (rh) writes:[color=blue]
              > Alternatively, if circumstance or preference implores a switch/case
              > structure:
              > switch (x) {
              > case ( ( 1 <= x && x <= 10 ) ? x : x+1 ):
              > alert("case 1-10: " + x);
              > break;
              > case (11):
              > case (14):
              > case (16):
              > alert("case 11,14, or 16: " + x);
              > break;
              > default:
              > alert("None of the above: " + x);
              > }[/color]

              Clever. I knew that in JavaScript the controlling expression of a
              switch does not have to have integer type (as in C) but did not
              realize that it does not have to be a constant expression. I guess
              when you don't want to compile your switch statement into a jump
              table, it's not important that the labels be integer literals :)

              However, this idiom is IMHO overly clever. It takes a few
              moments to see that it really does the right thing.

              --
              Chris Jeris cjeris@oinvzer. net Apply (1 6 2 4)(3 7) to domain to reply.

              Comment

              • rh

                #8
                Re: Switch as a Select Case

                Christopher Jeris <cjeris@oinvzer .net> wrote in message news:<ubrpf3gtd .fsf@oinvzer.ne t>...[color=blue]
                > codeHanger@yaho o.ca (rh) writes:[color=green]
                > > Alternatively, if circumstance or preference implores a switch/case
                > > structure:
                > > switch (x) {
                > > case ( ( 1 <= x && x <= 10 ) ? x : x+1 ):
                > > alert("case 1-10: " + x);
                > > break;
                > > case (11):
                > > case (14):
                > > case (16):
                > > alert("case 11,14, or 16: " + x);
                > > break;
                > > default:
                > > alert("None of the above: " + x);
                > > }[/color]
                >
                > Clever. I knew that in JavaScript the controlling expression of a
                > switch does not have to have integer type (as in C) but did not
                > realize that it does not have to be a constant expression. I guess
                > when you don't want to compile your switch statement into a jump
                > table, it's not important that the labels be integer literals :)[/color]

                The common "label" description doesn't really lead one to realize that
                and expression can be used. That's why I thought it might be
                worthwhile to provide an example.

                Whether a particular construct meets efficiency and other coding
                requirements is a decision that's up to the (hopefully well-informed)
                author.
                [color=blue]
                >
                > However, this idiom is IMHO overly clever. It takes a few
                > moments to see that it really does the right thing.[/color]

                The following Javascript statement:

                x = x || 1;

                would likely take a few moments for the uninitiated to determine what
                it does, let alone whether it does the "right thing". I don't believe
                that stands in the way of it being fully utilized by those familiar
                and comfortable with the fundamentals of the language.

                ../rh

                Comment

                • rh

                  #9
                  Re: Switch as a Select Case

                  Lasse Reichstein Nielsen <lrn@hotpop.com > wrote in message news:<brpga59y. fsf@hotpop.com> ...[color=blue]
                  > Keith Bowes <do.not@spam.me > writes:
                  >[color=green]
                  > > Christopher Jeris wrote:[color=darkred]
                  > >> JavaScript's syntax is based on that of C, and as in C,
                  > >> there is no syntactic sugar for switch statements.[/color]
                  > >
                  > > I disagree.[/color]
                  >
                  > With what? That the syntax is based on that of C (it is, although
                  > indirectly through the syntax of Java), or that there is no syntactic
                  > sugar for switch statements (there almost isn't - except that the
                  > values of a case can be arbitrary expressions)?
                  >
                  > What you seem to be disagreeing with, is that it should be like that
                  > (and I agree). For a scripting language, the options are too restrictive,
                  > which is probably why we so rarely see switches.
                  >[/color]

                  Then again, at the other extreme, some scripting languages don't have
                  a switch construct -- e.g., Perl.

                  I'm not sure of the reason that switch isn't more commonly used in
                  Javascript. In the absence of an IDE editor, they can be a little bit
                  awkward to construct, and that wouldn't change a whole lot even if
                  "range sugar" was available.

                  A major advantage of switch is that it provides encapusulation and
                  clear delineation of the set of alternatives under current
                  consideration. That's something that can get obscured to some degree,
                  even with with well-formatted block structure, in code that uses
                  if/else exclusively to process conditionals.

                  ../rh
                  [color=blue]
                  > /L[/color]

                  Comment

                  • Christopher Jeris

                    #10
                    Re: Switch as a Select Case

                    codeHanger@yaho o.ca (rh) writes:[color=blue]
                    > A major advantage of switch is that it provides encapusulation and
                    > clear delineation of the set of alternatives under current
                    > consideration. That's something that can get obscured to some degree,
                    > even with with well-formatted block structure, in code that uses
                    > if/else exclusively to process conditionals.[/color]

                    \begin{sententi ous}
                    Since the correct programming language has already exhibited the
                    correct control structure to handle multiple alternatives, any
                    variations on it are at best superfluous. I refer of course to
                    the 'cond' of the Lisp family, which expresses a sequence of
                    if-else decisions symmetrically:

                    (cond ((<= 1 x 10) (do-something-with x))
                    ((or (= x 11)
                    (= x 14)
                    (= x 16)) (do-something-else-with x))
                    (t (complain)))

                    \end{sententiou s} % :)

                    --
                    Chris Jeris cjeris@oinvzer. net Apply (1 6 2 4)(3 7) to domain to reply.

                    Comment

                    • rh

                      #11
                      Re: Switch as a Select Case

                      Christopher Jeris <cjeris@oinvzer .net> wrote in message news:<uvfnntm2t .fsf@oinvzer.ne t>...[color=blue]
                      > codeHanger@yaho o.ca (rh) writes:[color=green]
                      > > A major advantage of switch is that it provides encapusulation and
                      > > clear delineation of the set of alternatives under current
                      > > consideration. That's something that can get obscured to some degree,
                      > > even with with well-formatted block structure, in code that uses
                      > > if/else exclusively to process conditionals.[/color]
                      >
                      > \begin{sententi ous}
                      > Since the correct programming language has already exhibited the
                      > correct control structure to handle multiple alternatives, any
                      > variations on it are at best superfluous. I refer of course to
                      > the 'cond' of the Lisp family, which expresses a sequence of
                      > if-else decisions symmetrically:
                      >
                      > (cond ((<= 1 x 10) (do-something-with x))
                      > ((or (= x 11)
                      > (= x 14)
                      > (= x 16)) (do-something-else-with x))
                      > (t (complain)))
                      >
                      > \end{sententiou s} % :)[/color]

                      <facetious>
                      I have a recollection of an old cartoon with the caption:

                      "Whenever you see a bunch of parentheses, you can always be sure
                      they're up to no good!".

                      Even Charlie Brown knew the Lisp family was trouble. :-)
                      </facetious>

                      ../rh

                      Comment

                      • Thomas 'PointedEars' Lahn

                        #12
                        Re: Switch as a Select Case

                        rh wrote:
                        [color=blue]
                        > The following Javascript statement:
                        >
                        > x = x || 1;
                        >
                        > would likely take a few moments for the uninitiated to determine what
                        > it does, let alone whether it does the "right thing". I don't believe
                        > that stands in the way of it being fully utilized by those familiar
                        > and comfortable with the fundamentals of the language.[/color]

                        Are you sure you know what you are doing?

                        | Error: x is not defined
                        | Source File: javascript:aler t(x || 1)
                        | Line: 1

                        | Error: x is not defined
                        | Source File: javascript:x = x || 1; alert(x);
                        | Line: 1

                        It works only if "x" has been declared before (even the "undefined"
                        value suffices while no declaration does not), e.g. if "x" is the
                        identifier of an argument, you may easily specify a default value
                        of 1 for that argument as the "undefined" value evaluates to "false".


                        PointedEars

                        Comment

                        • Douglas Crockford

                          #13
                          Re: Switch as a Select Case

                          > > JavaScript's syntax is based on that of C, and as in C,[color=blue][color=green]
                          > > there is no syntactic sugar for switch statements.[/color]
                          >
                          > I disagree. The convenient syntaxes used in BASIC, Pascal, etc. existed
                          > before C was a language. C was designed to be very low-level, where
                          > efficiency is paramount; JavaScript is an interpreted language for web
                          > pages and is well known to be inefficient, and therefore there is no
                          > reason for stodgily keeping such inconveniences. Furthermore, GCC's
                          > version of C has the ability for ranges, with a syntax very similar to
                          > Pascal's.[/color]

                          Perhaps you disagree because you don't know what syntax is. It is a fact that
                          JavaScript's syntax is based on C's. JavaScript extends the switch statement by
                          allowing the case values to be expressions, while C requires that they resolve
                          at runtime to integers.



                          Comment

                          • Douglas Crockford

                            #14
                            Re: Switch as a Select Case

                            > I have a recollection of an old cartoon with the caption:[color=blue]
                            >
                            > "Whenever you see a bunch of parentheses, you can always be sure
                            > they're up to no good!".[/color]

                            October 18, 1977

                            Panel 1:

                            [ ] [ ] [ ]
                            [ ] [ ] [ ]

                            (Sally is writing)

                            Panel 2:

                            (Charlie Brown enters)

                            SALLY:
                            I'm practicing my brackets...

                            Panel 3:

                            SALLY:
                            Do you know that brackets are always used in pairs?

                            Panel 4:
                            SALLY:
                            If you ever see a bracket by itself you can be sure it's up to no good!

                            Copyright 1977 United Feature Syndicate, Inc.

                            Comment

                            • Douglas Crockford

                              #15
                              Re: Switch as a Select Case

                              > The following Javascript statement:[color=blue]
                              >
                              > x = x || 1;
                              >
                              > would likely take a few moments for the uninitiated to determine what
                              > it does, let alone whether it does the "right thing". I don't believe
                              > that stands in the way of it being fully utilized by those familiar
                              > and comfortable with the fundamentals of the language.[/color]

                              I completely agree with that. I teach that || is the 'default' operator, and
                              that && is the 'guard' operator. With a proper education, these idioms produce
                              simplier, better programs.



                              Comment

                              Working...