Jack Ryu wrote:Hy everyone, I have a simple question about JavaScript but it can apply to Java or any programming language for that matter.
Not true unfortunately, for the reason Campbell mentioned.
When do you use an If statement vs and select case statement.
It's often a matter of style, but my general rule is: Use
switch when:
(a) You can.
(b) There are more than two options.
(c) It makes the logic more readable.
And in Java, (a) precludes quite a lot of cases where you might otherwise
want to use it, because the value in each
case statement MUST be a "compile time constant" - ie, a literal, primitive constant, or the name of an
enum instance.
(b) is fairly straightforward: there's not much point in using a
switch where a simple
if will do. In some cases where there are exactly 3 options, I will use a compound
conditional operator because it's a bit more compact, but it's very much a matter of style.
(c) is where the "style" really comes in. IMO,
switch is almost always clearer than a long
if...else chain, but not everyone will agree with me.
HIH
Winston