Switch as a Select Case

Discussion in 'Javascript' started by Robert Scheer, Jan 6, 2004.

  1. 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
    Robert Scheer, Jan 6, 2004
    #1
    1. Advertising

  2. Robert Scheer

    McKirahan Guest

    "Robert Scheer" <> wrote in message
    news:...
    > 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


    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
    }
    McKirahan, Jan 6, 2004
    #2
    1. Advertising

  3. (Robert Scheer) writes:
    > 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


    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 Apply (1 6 2 4)(3 7) to domain to reply.
    Christopher Jeris, Jan 6, 2004
    #3
  4. Robert Scheer

    Keith Bowes Guest

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


    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.
    Keith Bowes, Jan 6, 2004
    #4
  5. Robert Scheer

    rh Guest

    Christopher Jeris <> wrote in message news:<>...
    > (Robert Scheer) writes:
    > > 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

    >


    <...>

    > 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
    > }


    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
    rh, Jan 6, 2004
    #5
  6. Keith Bowes <> writes:

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

    >
    > I disagree.


    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 -
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
    'Faith without judgement merely degrades the spirit divine.'
    Lasse Reichstein Nielsen, Jan 7, 2004
    #6
  7. (rh) writes:
    > 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);
    > }


    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 Apply (1 6 2 4)(3 7) to domain to reply.
    Christopher Jeris, Jan 7, 2004
    #7
  8. Robert Scheer

    rh Guest

    Christopher Jeris <> wrote in message news:<>...
    > (rh) writes:
    > > 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);
    > > }

    >
    > 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 :)


    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.

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


    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
    rh, Jan 7, 2004
    #8
  9. Robert Scheer

    rh Guest

    Lasse Reichstein Nielsen <> wrote in message news:<>...
    > Keith Bowes <> writes:
    >
    > > Christopher Jeris wrote:
    > >> JavaScript's syntax is based on that of C, and as in C,
    > >> there is no syntactic sugar for switch statements.

    > >
    > > I disagree.

    >
    > 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.
    >


    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

    > /L
    rh, Jan 7, 2004
    #9
  10. (rh) writes:
    > 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.


    \begin{sententious}
    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{sententious} % :)

    --
    Chris Jeris Apply (1 6 2 4)(3 7) to domain to reply.
    Christopher Jeris, Jan 7, 2004
    #10
  11. Robert Scheer

    rh Guest

    Christopher Jeris <> wrote in message news:<>...
    > (rh) writes:
    > > 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.

    >
    > \begin{sententious}
    > 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{sententious} % :)


    <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
    rh, Jan 8, 2004
    #11
  12. rh wrote:

    > 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.


    Are you sure you know what you are doing?

    | Error: x is not defined
    | Source File: javascript:alert(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
    Thomas 'PointedEars' Lahn, Jan 19, 2004
    #12
  13. JRS: In article <>, seen in
    news:comp.lang.javascript, Thomas 'PointedEars' Lahn
    <> posted at Mon, 19 Jan 2004 08:24:20 :-
    >rh wrote:
    > ...
    >Are you sure you know what you are doing?
    > ...
    >PointedEars


    The above nicely illustrates why an attribution should not be
    trivialised.

    PE is responding to an article from 12 days earlier, one which most
    readers will have forgotten. Giving the attribution date would have
    made the situation clear.

    Moreover, 'rh' is rather an inadequate personal identifier; giving the
    attribution E-address would have helped, since that is in this case more
    memorable - .

    BTW, rh's first article in this thread is the one alluded to in my
    article <> "Re: Another doubt when
    using switch" posted here at Fri, 16 Jan 2004 23:16:23, for which
    thanks.

    --
    © John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME ©
    Web <URL:http://www.uwasa.fi/~ts/http/tsfaq.html> -> Timo Salmi: Usenet Q&A.
    Web <URL:http://www.merlyn.demon.co.uk/news-use.htm> : about usage of News.
    No Encoding. Quotes before replies. Snip well. Write clearly. Don't Mail News.
    Dr John Stockton, Jan 19, 2004
    #13
  14. > > JavaScript's syntax is based on that of C, and as in C,
    > > there is no syntactic sugar for switch statements.

    >
    > 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.


    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.

    http://www.crockford.com/javascript/javascript.html
    Douglas Crockford, Jan 19, 2004
    #14
  15. > 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!".


    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.
    Douglas Crockford, Jan 19, 2004
    #15
  16. > 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.


    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.

    http://www.crockford.com/javascript/survey.html
    Douglas Crockford, Jan 19, 2004
    #16
  17. Robert Scheer

    rh Guest

    Thomas 'PointedEars' Lahn <> wrote in message news:<>...

    > Are you sure you know what you are doing?


    Well, I'm currently responding to this post, so that should be enough
    to put the answer pretty high on the negative scale. :-/

    >
    > | Error: x is not defined
    > | Source File: javascript:alert(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".
    >
    >


    As you note, the form "param = param || defaultValue;" can be used to
    default parameter values that have not been supplied on a function
    call -- a common requirement given that the there is, by design, no
    signature correspondence required between the caller and callee in
    javascript.

    Within this intended context of use, undeclared variables are
    irrelevant (or a progamming error).

    ../rh
    rh, Jan 19, 2004
    #17
  18. rh wrote:

    > Thomas 'PointedEars' Lahn <> wrote in message
    > news:<>...


    Please shorten your attribution. People who know what a message-id is
    know where to find it.

    >> Are you sure you know what you are doing?

    >
    > Well, I'm currently responding to this post, so that should be
    > enough to put the answer pretty high on the negative scale. :-/


    What is that supposed to mean?

    >>> x = x || 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".

    >
    > As you note, the form "param = param || defaultValue;" can be used to
    > default parameter values


    They are called "arguments" in JavaScript (1.x).

    > that have not been supplied on a function call -- a common
    > requirement given that the there is, by design, no signature
    > correspondence required between the caller and callee in javascript.


    Did I not write that?

    > Within this intended context of use, undeclared variables are
    > irrelevant (or a progamming error).


    Non sequitur.

    var x = x || 1;

    triggers an error if "x" has not been declared before even *this*
    statement was designed to declare and define "x". So the possibilities
    of application for this shortcut are in fact limited, and nothing more I
    wanted to say.


    PointedEars
    Thomas 'PointedEars' Lahn, Jan 20, 2004
    #18
  19. Thomas 'PointedEars' Lahn <> writes:

    > rh wrote:
    >> Well, I'm currently responding to this post, so that should be
    >> enough to put the answer pretty high on the negative scale. :-/

    >
    > What is that supposed to mean?


    I believe it was an elegant repartee to what could easiliy be seen as
    a patronizing question.

    >> As you note, the form "param = param || defaultValue;" can be used to
    >> default parameter values

    >
    > They are called "arguments" in JavaScript (1.x).


    Thank you for that information. In ECMA 262, they are called
    parameters. As a programming language theoretician, I would say the
    two are roughly equivalent. One does distinguish between formal
    parameters and actual parameters, where the actual parameters
    would be equivalent to the arguments ... but that is at the
    theoretical level. In normal language, I would not distinguish.

    > var x = x || 1;
    >
    > triggers an error if "x" has not been declared before even *this*
    > statement was designed to declare and define "x".


    Have you tested it?
    It shouldn't give an error according to ECMA 262, and it doesn't in
    Opera, IE 6, Mozilla FB or Netscape 4. So, no.

    /L
    --
    Lasse Reichstein Nielsen -
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
    'Faith without judgement merely degrades the spirit divine.'
    Lasse Reichstein Nielsen, Jan 20, 2004
    #19
  20. Lasse Reichstein Nielsen wrote:

    > Thomas 'PointedEars' Lahn <> writes:
    >> var x = x || 1;
    >>
    >> triggers an error if "x" has not been declared before even *this*
    >> statement was designed to declare and define "x".

    >
    > Have you tested it?


    I thought I had before.

    > It shouldn't give an error according to ECMA 262, and it doesn't in
    > Opera, IE 6, Mozilla FB or Netscape 4. So, no.


    ACK, memory failure.


    PointedEars
    Thomas 'PointedEars' Lahn, Jan 20, 2004
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Tee
    Replies:
    3
    Views:
    7,769
    Herfried K. Wagner [MVP]
    Jun 23, 2004
  2. Lakshmi Narayanan.R

    "Case 1 To 5" in Select case, giving Error!!. Why?

    Lakshmi Narayanan.R, Mar 2, 2005, in forum: ASP General
    Replies:
    10
    Views:
    333
    Bob Barrows [MVP]
    Mar 4, 2005
  3. aa
    Replies:
    14
    Views:
    312
  4. Switch Within A Switch

    , Apr 22, 2006, in forum: Javascript
    Replies:
    7
    Views:
    95
    Lasse Reichstein Nielsen
    Apr 22, 2006
  5. richard

    switch or select case and code inside it

    richard, Nov 4, 2008, in forum: Javascript
    Replies:
    7
    Views:
    107
    Gregor Kofler
    Nov 6, 2008
Loading...

Share This Page