473,394 Members | 1,658 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

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
Jul 20 '05 #1
19 8044
"Robert Scheer" <rb******@my-deja.com> wrote in message
news:cf**************************@posting.google.c om...
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
}
Jul 20 '05 #2
rb******@my-deja.com (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 cj****@oinvzer.net Apply (1 6 2 4)(3 7) to domain to reply.

Jul 20 '05 #3
rh
Christopher Jeris <cj****@oinvzer.net> wrote in message news:<uk***********@oinvzer.net>...
rb******@my-deja.com (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
Jul 20 '05 #4
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.

Jul 20 '05 #5
Keith Bowes <do****@spam.me> 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 - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #6
co********@yahoo.ca (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 cj****@oinvzer.net Apply (1 6 2 4)(3 7) to domain to reply.

Jul 20 '05 #7
rh
Christopher Jeris <cj****@oinvzer.net> wrote in message news:<ub***********@oinvzer.net>...
co********@yahoo.ca (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
Jul 20 '05 #8
rh
Lasse Reichstein Nielsen <lr*@hotpop.com> wrote in message news:<br**********@hotpop.com>...
Keith Bowes <do****@spam.me> 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

Jul 20 '05 #9
co********@yahoo.ca (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 cj****@oinvzer.net Apply (1 6 2 4)(3 7) to domain to reply.
Jul 20 '05 #10
rh
Christopher Jeris <cj****@oinvzer.net> wrote in message news:<uv***********@oinvzer.net>...
co********@yahoo.ca (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
Jul 20 '05 #11
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
Jul 20 '05 #12
> > 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

Jul 20 '05 #13
> 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.

Jul 20 '05 #14
> 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

Jul 20 '05 #15
JRS: In article <40**************@PointedEars.de>, seen in
news:comp.lang.javascript, Thomas 'PointedEars' Lahn
<Po*********@web.de> 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 - co********@yahoo.ca.

BTW, rh's first article in this thread is the one alluded to in my
article <UP**************@merlyn.demon.co.uk> "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.
Jul 20 '05 #16
rh
Thomas 'PointedEars' Lahn <Po*********@web.de> wrote in message news:<40**************@PointedEars.de>...
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
Jul 20 '05 #17
rh wrote:
Thomas 'PointedEars' Lahn <Po*********@web.de> wrote in message
news:<40**************@PointedEars.de>...
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
Jul 20 '05 #18
Thomas 'PointedEars' Lahn <Po*********@web.de> 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 - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #19
Lasse Reichstein Nielsen wrote:
Thomas 'PointedEars' Lahn <Po*********@web.de> 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
Jul 20 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Keon | last post by:
Hoi Is there a way to use a select case in a javascript? I already tried it with switch intHulp = 1; switch (intHulp) { case 1: setTimeout("document.getElementById('myIframe').src...
3
by: pgraeve | last post by:
I am a convert from VB to C# so bear with me on this "conversion" question C# switch statement seems to be the closest relative to VB's Select Case. I used VB's Select Case statement liberally. ...
16
by: ME | last post by:
In C# the following code generates a compiler error ("A constant value is expected"): public void Test(string value) { switch (value) { case SimpleEnum.One.ToString(): MessageBox.Show("Test...
2
by: Dave Markle | last post by:
Good afternoon. I was just going through my code, analyzing it with FXCop, and FxCop gave me the following error on this code: MY CODE: Select Case termYears Case 5 : retVal.Append("1") Case...
21
beacon
by: beacon | last post by:
Hello to everybody, I have a section on a form that has 10 questions, numbered 1-10, with 3 option buttons per question. Each of the option buttons have the same response (Yes, No, Don't know),...
5
by: richard | last post by:
I've been tossing around the idea now that maybe my problem might be better resolved by using the "select case"/switch command. The only problem is, all the dozens of sites I've seen so far only...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.