Switch as a Select Case

R

Robert Scheer

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
 
M

McKirahan

Robert Scheer said:
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
}
 
C

Christopher Jeris

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

Keith Bowes

Christopher said:
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.
 
R

rh

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
 
L

Lasse Reichstein Nielsen

Keith Bowes said:
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
 
C

Christopher Jeris

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

rh

Christopher Jeris said:
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
 
R

rh

Lasse Reichstein Nielsen said:
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
 
C

Christopher Jeris

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} % :)
 
R

rh

Christopher Jeris said:
\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
 
T

Thomas 'PointedEars' Lahn

rh said:
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
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
Thomas 'PointedEars' Lahn
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 - (e-mail address removed).

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

Douglas Crockford

JavaScript's syntax is based on that of C, and as in C,
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
 
D

Douglas Crockford

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

Douglas Crockford

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
 
R

rh

Thomas 'PointedEars' Lahn said:
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
 
T

Thomas 'PointedEars' Lahn

rh said:

Please shorten your attribution. People who know what a message-id is
know where to find it.
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?
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
 
L

Lasse Reichstein Nielsen

Thomas 'PointedEars' Lahn said:
What is that supposed to mean?

I believe it was an elegant repartee to what could easiliy be seen as
a patronizing question.
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top