473,385 Members | 2,013 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,385 software developers and data experts.

Switch statement help

Hi - how can I get a switch statement to look for a range of values?

I have:

function payCalc(field, field2)
switch(field.value)
{
case 0-50: field2.value="lower band";
case 51-99: field2.value="mid band";
case 100-9999: field2.value="high band";
}

But this doesn't seem to work.

Thanks for any help,

Mark

*** Sent via Developersdex http://www.developersdex.com ***
Jan 9 '06 #1
24 4334
Mark wrote on 09 jan 2006 in comp.lang.javascript:
Hi - how can I get a switch statement to look for a range of values?

I have:

function payCalc(field, field2)
switch(field.value)
{
case 0-50: field2.value="lower band";
case 51-99: field2.value="mid band";
case 100-9999: field2.value="high band";
}

But this doesn't seem to work.


Switch is only handy for the godly that have read the specs.

For us mere mortals, to lazy to read them, use:

field2.value =
(field.value<0) ? "out-of-range" :
(field.value<51) ? "lower band" :
(field.value<100) ? "mid band" :
(field.value<10000)? "high band" :
"out-of-range" ;

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jan 9 '06 #2
VK

Mark wrote:
Hi - how can I get a switch statement to look for a range of values?


"switch" statement doesn't directly support ranges (like in VBS / VBA).
But you can work around that by comparing the case with true:

var num = 8000;

switch(true) {
case num>=0&&num<=51:
alert(1); break;
case num<=99:
alert(2); break;
case num<=9999:
alert(3); break;
default:
alert('Out of range');
}

P.S. Unless you want to use (as suggested) more wide spread if-else if
- else block.

P.P.S. Also remember a very annoying cross-language bug in switch
construct: it executes all underlaying branches unless you stop it with
"break" statement.

Jan 9 '06 #3

VK wrote:

[snip]
P.P.S. Also remember a very annoying cross-language bug in switch
construct: it executes all underlaying branches unless you stop it with
"break" statement.

[snip]

Hello VK

Just interested in why you consider this to be a "bug"?

If I understand para 12.11 of the ECMA spec correctly
(<URL:http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf>,
the production for a CaseClause or DefaultClause does not require the
"break" Statement to be included.

Further, leaving out the break statement can IMHO be useful sometimes
(if for instance you want a given Statement to be executed for more
than one case).

So perhaps rather than "bug", do you mean: "source of potential errors
for the unwary"?

Regards

Julian Turner

Jan 9 '06 #4
VK

Julian Turner wrote:
VK wrote:

[snip]
P.P.S. Also remember a very annoying cross-language bug in switch
construct: it executes all underlaying branches unless you stop it with
"break" statement.

[snip]

Hello VK

Just interested in why you consider this to be a "bug"?


As I escaped the classical Comp.Sci. education I dare to call bug on
bug and sh** on sh** if I feel so :-))
In the particular I do not consider a nonsense to magically become a
lore just of being put in written (whoever wasted inks for it).

This has nothing to do with ECMA though - it's all the same: up to the
most pre-historic languages.
Why do I think it's a bug? Because it goes against the common
programming logic - and this is why people keep forgetting about
break's.

It's like having to put break after each function body so execution
wouldn't jump on underlaying function:
function foo() {
// ...
}
break;
function bar() {
// ...
}

- and w/o break after foo() we would immediately execute bar(). A lot
of sense? None. The same amount in
case X : ...; break; // IMHO

A perfect case of reversed logic for me. That would have some sense
maybe to have a flag to "continue" execution of underlaying branches -
but not a current annoyance twist.

IMHO IMHO IMHO

Jan 9 '06 #5
VK

VK wrote:
A perfect case of reversed logic for me. That would have some sense
maybe to have a flag to "continue" execution of underlaying branches -
but not the current annoyance twist.


Also it breaks apart the boolean logic rules used in programming
languages:

case 10 :
case 20:
case 30:
default:

If switch happened to be equal 10, then after the first case: it also
equals to 20 and 30 ! (by the execution logic) As if program on its one
behalf would replace in:
if (statement1)
else if (statement2) {}
else if (statement3) {}
else {}
all statements with (true). Think how much would you like it! ;-)

Jan 9 '06 #6

VK wrote:
This has nothing to do with ECMA though - it's all the same: up to the
most pre-historic languages.
Fair enough, fall-through (missing "break" statement) is a feature of
C++ and Java as well - e.g.

<URL:http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.11>
Why do I think it's a bug? Because it goes against the common
programming logic - and this is why people keep forgetting about
break's.


You are entitled to your opinion. I thought, IHMO, it might just be
worth considering identifying it as an opinion, to avoid possible
confusion.

Nevertheless, I would agree that "fall-though" (despite its uses) is
not obvious from the structure of the switch statement, and so could
perhaps lead to code that is harder to follow.

Regards

Julian Turner

Jan 9 '06 #7
VK

Julian Turner wrote:
VK wrote:
Why do I think it's a bug? Because it goes against the common
programming logic - and this is why people keep forgetting about
break's.


You are entitled to your opinion. I thought, IHMO, it might just be
worth considering identifying it as an opinion, to avoid possible
confusion.


Fair enough :-)
I guess from now on I'll be using terms not so heavily connected with
the programming entities. Then the "switch" behavior could be called
"common annoyance" (taken from the Firefox vocabulary).

Jan 9 '06 #8
VK

Lee wrote:
case 10 :
case 20:
case 30:
default:

If switch happened to be equal 10, then after the first case: it also
equals to 20 and 30 !


As usual, you've done a fine job of convincing us that you don't
understand what you're talking about. The usage in your example
doesn't tell us that the switch equals 10, 20, and 30, it tells
us that 10, 20 and 30 are to be handled in the same way. It's
just that sort of distinction that you seem to have trouble with.


Boy, that was just a short scheme to illustrate my point, not a code to
execute.
Sapienti sat - but if it's not the case then here a full scale code:

<script type="text/javascript">
var v = 10;
switch (v) {
case 10 : alert("v equals 10");
case 20 : alert("v equals 20");
case 30 : alert("v equals 30");
default: alert("v is out of range");
}
</script>

Jan 9 '06 #9
Mark wrote:

"I have:
function payCalc(field, field2)
switch(field.value)
{
case 0-50: field2.value="lower band";
case 51-99: field2.value="mid band";
case 100-9999: field2.value="high band";
}"

Shouldn't the switch statement within the function also be enclosed in
curly brackets ? Like this:

function payCalc(field, field2)
{
switch(field.value)
{
case 0-50: field2.value="lower band";
case 51-99: field2.value="mid band";
case 100-9999: field2.value="high band";
}
}

In addition to using a break or return statement after each case, isn't
there also suppose to be a default case at the end ? Or is that not
necessary ?

Later, Art.

Jan 9 '06 #10
X l e c t r i c wrote on 09 jan 2006 in comp.lang.javascript:
case 0-50: field2.value="lower band";
case 51-99: field2.value="mid band";
case 100-9999: field2.value="high band";


Besides all that is said,
this means:

case -49: field2.value="lower band";
case -48: field2.value="mid band";
case -9899: field2.value="high band";

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jan 9 '06 #11
In article <11****************@storefull-3335.bay.webtv.net>,
Xl******@webtv.net (X l e c t r i c) wrote:
Mark wrote:

"I have:
function payCalc(field, field2)
switch(field.value)
{
case 0-50: field2.value="lower band";
case 51-99: field2.value="mid band";
case 100-9999: field2.value="high band";
}"

Shouldn't the switch statement within the function also be enclosed in
curly brackets ? Like this:

function payCalc(field, field2)
{
switch(field.value)
{
case 0-50: field2.value="lower band";
case 51-99: field2.value="mid band";
case 100-9999: field2.value="high band";
}
}
I suppose so, strickly, tho I wouldn't lay it out like that. Of course
"case 0-50:" does not work.
In addition to using a break or return statement after each case, isn't
there also suppose to be a default case at the end ? Or is that not
necessary ?


Only if you want one. If you leave it out and the value matches none of
the cases then the switch does nothing. This can be useful depending on
what you want.

Certainly the break should be required. That does allow you to do this
sort of thing:

switch (value)
{

case 1:
case 2:
x = 3;
break;

case 15:
x = 8;
break;

}

In fact in this example you don't need the send break, but it's best to
add it for the day when you add another case. Code that's gonna live
more than 15 mins should be written with a view to future maintenance.

-- tim
Jan 9 '06 #12
"Julian Turner" <ju****@baconbutty.com> writes:
VK wrote:

[snip]
P.P.S. Also remember a very annoying cross-language bug in switch
construct: it executes all underlaying branches unless you stop it with
"break" statement.
Just interested in why you consider this to be a "bug"?
It's not a bug.

It's just a very annoying and error prone feature that was introduced
in C a long time ago, back when brevity was a bigger virtue than
readability.
Further, leaving out the break statement can IMHO be useful sometimes
(if for instance you want a given Statement to be executed for more
than one case).
You could allow several cases for each branch, without needing
fallthrough between branches.

The few algorithms that can actually use fallthrough does not justify
the gazillion errors created by unwary programmers through the years.
So perhaps rather than "bug", do you mean: "source of potential errors
for the unwary"?


I don't speak for VK, but I mean that.

/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.'
Jan 9 '06 #13

Lasse Reichstein Nielsen wrote:

[snip]
You could allow several cases for each branch, without needing
fallthrough between branches.

The few algorithms that can actually use fallthrough does not justify
the gazillion errors created by unwary programmers through the years.


Fair point. I have found a few instances where fall-through was a
potentially useful option, but have tended to avoid it as in all cases
there were clearer alternative ways of doing the same thing.

Regards

Julian Turner

Jan 9 '06 #14
In article <ir**********@hotpop.com>,
Lasse Reichstein Nielsen <lr*@hotpop.com> wrote:
"Julian Turner" <ju****@baconbutty.com> writes:
VK wrote:

[snip]
P.P.S. Also remember a very annoying cross-language bug in switch
construct: it executes all underlaying branches unless you stop it with
"break" statement.

Just interested in why you consider this to be a "bug"?


It's not a bug.

It's just a very annoying and error prone feature that was introduced
in C a long time ago, back when brevity was a bigger virtue than
readability.


It's not an annoying and error-prone feature. It's very useful. It adds
flexibility. I contrast this with Pascal, which had a number of shitty
irritations such as this (i.e., not needing the break as it was
inherently there) in the name of language "purity".

-- tim
Jan 9 '06 #15
Evertjan. wrote:
X l e c t r i c wrote on 09 jan 2006 in comp.lang.javascript:
case 0-50: field2.value="lower band";
case 51-99: field2.value="mid band";
case 100-9999: field2.value="high band";


Besides all that is said,
this means:

case -49: field2.value="lower band";
case -48: field2.value="mid band";
case -9899: field2.value="high band";

or even:

case -49: case -48: case -9899:
field2.value = "high band";

:)
Jan 9 '06 #16
VK

Lee wrote:
It's a very handy way to identify people who don't know how to
read a manual. Programmers should avoid guessing how features
work.


As it was pointed out already, it is not how do things work - it's
about how the logic works.

"If *this* is True than do this, otherwise if *that* is true then do
that, if nothing is true then do *this thing* "

But you have to remember that there is *one* exception implementing a
perverted logic: "if this is true, then anything else is also true even
if it's false".

Easy to remember - but also easy to forget because 99.99% of time you
are still dealing with the normal machine logic.

One of things to pin near of your monitor I guess - or simply avoid to
use :-)

Jan 9 '06 #17
Lee <RE**************@cox.net> writes:
Lasse Reichstein Nielsen said:
The few algorithms that can actually use fallthrough does not justify
the gazillion errors created by unwary programmers through the years.


It's a very handy way to identify people who don't know how to
read a manual. Programmers should avoid guessing how features
work.


Absolutely. But even the ones who do know can forget, and the more
illogical a feature is, and the more it differs from other languages
that the programmer also use regularly, the more will forget it.

But while we are at guessing, fallthrough in a switch fails the "least
surprise" test of good design. If shown a switch in any other syntax,
if I should make a guess, I would not guess that there was fallthrough.

/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.'
Jan 10 '06 #18
Lasse Reichstein Nielsen wrote:
Lee <RE**************@cox.net> writes:
Lasse Reichstein Nielsen said:
The few algorithms that can actually use fallthrough does not
justify the gazillion errors created by unwary programmers
through the years.

It's a very handy way to identify people who don't know how to
read a manual. Programmers should avoid guessing how features
work.


Absolutely. But even the ones who do know can forget, and the
more illogical a feature is, and the more it differs from other
languages that the programmer also use regularly, the more will
forget it.

But while we are at guessing, fallthrough in a switch fails the
"least surprise" test of good design. If shown a switch in any
other syntax, if I should make a guess, I would not guess that
there was fallthrough.


As you have pointed out that switch was adopted from C, and had
fall-through originally, the design error may have been retaining the
same keyword for versions that did not have fall-through.

Richard.
Jan 10 '06 #19
Lasse Reichstein Nielsen wrote:
Lee <RE**************@cox.net> writes:
Lasse Reichstein Nielsen said:
The few algorithms that can actually use fallthrough does not justify
the gazillion errors created by unwary programmers through the years. It's a very handy way to identify people who don't know how to
read a manual. Programmers should avoid guessing how features
work.


Absolutely. But even the ones who do know can forget, and the more
illogical a feature is, and the more it differs from other languages
that the programmer also use regularly, the more will forget it.


While I always found the break statement to be quite natural (even
before I knew there was fall through) because that's how I learned it
from the get go, I did recently fall into an error were I forgot to
place the break statements in a multiple case scenario. This was causing
my default code to run every time the script was executed, and was
annoying for quite a few minutes. I felt pretty silly after I had
realized the mistake.

But while we are at guessing, fallthrough in a switch fails the "least
surprise" test of good design. If shown a switch in any other syntax,
if I should make a guess, I would not guess that there was fallthrough.


Since it is argued that there is merit in having fall through sometimes,
I wonder if the fix could be something like to remove the necessity of
the break keyword to prevent fall through, but add the continue keyword
to enable it (of course this would break existing code that uses fall
through - so it's just theoretical).

This would seem to make more sense to me, since fall through is so
infrequently used, and I would not have run into that annoying bug in my
code if this was the case.

Kevin N.
Jan 10 '06 #20
Lee <RE**************@cox.net> writes:
That's because you're thinking in terms of "if then else".
Absolutely. That's the way similar constructs are described in other
languages like Pascal, Scheme, Ada, and even in Fortran which predates
C.

<URL:http://www.xploiter.com/mirrors/pascal/pas026.htm>
<URL:http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-7.html#%_sec_4.2.1>
<URL:http://www.adaic.org/standards/95lrm/html/RM-5-4.html>
<URL:http://csit1cwe.fsu.edu/extra_link/xlhpf/xlflrm64.htm#HDRCASECON>
The switch determines the entry point into a block of statements.
When you think about it that way, fallthrough is the expected
behavior.


You could say that C doesn't have a multiway conditional like the
languages above, and instead has a computed goto statement called
"switch". You would probably technically be right too

It's just that the multiway conditional is such a useful construct, as
its general adaption in pretty much any other language family
suggests, that you *will* try to simulate it with the nearest
equivalent in the language, especially when switch is so close. And
that was also the intention of the switch statment.

Quoting from "The Ansi C Languge, 2ed" (page 59):

"Falling trough from one case to another is not robust, being prone to
disintegration when the program is modified. With the exception of
multiple labels for a single computation, fall-throughs should be used
sparingly, and commented."
Again, C's switch is from a time when expressive power was more
important than readability or even maintainability. You could do some
things with fallthorough that you can't easily do without (without
duplicating code). But I would still much rather have had a continue
statement to mark the fallthrough than the absence of a break.

We just have to live with it. We don't have to like it :)

/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.'
Jan 10 '06 #21
Kevin Newman <Ca******@unFocus.com> writes:
Since it is argued that there is merit in having fall through
sometimes, I wonder if the fix could be something like to remove the
necessity of the break keyword to prevent fall through, but add the
continue keyword to enable it (of course this would break existing
code that uses fall through - so it's just theoretical).


Scaringly, I just suggested the exact same thing in another post,
before reading it here. It kindof suggests that it would be the
obvious solution :)

/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.'
Jan 10 '06 #22
Lasse Reichstein Nielsen wrote:
Scaringly, I just suggested the exact same thing in another post,
before reading it here. It kindof suggests that it would be the
obvious solution :)


It's fun when that happens. :-)

Kevin N.
Jan 11 '06 #23
VK

Kevin Newman wrote:
Lasse Reichstein Nielsen wrote:
Scaringly, I just suggested the exact same thing in another post,
before reading it here. It kindof suggests that it would be the
obvious solution :)


It's fun when that happens. :-)


And of course no credits to who really said it first (oh well - as
usual :-)

See my 2nd post in this thread:
<quote>
A perfect case of reversed logic for me. That would have some sense
maybe to have a flag to "continue" execution of underlaying branches -
but not a current annoyance twist.
</quote>

A regular destiny of a genius - he does the things, but others are
benefiting of it.

:-D

Jan 11 '06 #24
VK wrote:

"And of course no credits to who really said it first (oh well - as
usual :-)

See my 2nd post in this thread:
<quote>
A perfect case of reversed logic for me. That would have some sense
maybe to have a flag to "continue" execution of underlaying branches -
but not a current annoyance twist.
</quote>

A regular destiny of a genius - he does the things, but others are
benefiting of it.
:-D"

Be honest VK. You read that in Lee's manual, didn't you ?

Jan 11 '06 #25

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

Similar topics

35
by: Thomas Matthews | last post by:
Hi, My son is writing a program to move a character. He is using the numbers on the keypad to indicate the direction of movement: 7 8 9 4 5 6 1 2 3 Each number has a direction except...
17
by: prafulla | last post by:
Hi all, I don't have a copy of C standard at hand and so anyone of you can help me. I have always wondered how switch statements are so efficient in jumping to the right case (if any)? Can...
11
by: Scott C. Reynolds | last post by:
In VB6 you could do a SELECT CASE that would evaluate each case for truth and execute those statements, such as: SELECT CASE True case x > y: dosomestuff() case x = 5: dosomestuff() case y >...
19
by: rdavis7408 | last post by:
Hello, I have four textboxes that the user enters the price per gallon paid at the pump, the mileage per gallon and I would like to then calculate the cost per gallon and use a switch statement to...
2
by: Macca | last post by:
Hi, I have a switch statement that has 5+ case statements. Each of these case statements copies form one array to another. Rather than doing a separate try..catch statement for each case...
4
by: priyanka | last post by:
Hi there, I had a question. Is there any way of testing a string value in a switch statement. I have about 50 string values that can be in a string variable. I tried cheking them with the if...
5
by: Phuff | last post by:
Hey all, I need some direction help. I have a switch case statement that is seemingly my only option right now, but its too large and not easy to maintain the code. Here goes... I have part...
12
by: | last post by:
Is it fine to call another method from Switch? Eg. Switch (stringVar) { case ("a"): somVar = "whatever"; Another_Method(); //call another method return;
3
by: Drowningwater | last post by:
I'm writing a program and I've made a switch statement. I have several quesions: 1. I have a string variable and when I try to use that string variable with the switch function I get a compiling...
2
osward
by: osward | last post by:
Hello there, I am using phpnuke 8.0 to build my website, knowing little on php programing. I am assembling a module for my member which is basically cut and paste existing code section of...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.