View Full Version : Is the switch expression evaluated only once?

08-27-2004, 08:38 AM
If you compare:

switch(a * b){...}


var expression = a * b;

does storing 'expression' serve any purpose?

08-27-2004, 09:08 AM
function foo()
var a = 1;
var b = 2;
switch(a * b)
case 2: alert("evaluated once");a = 2;
case 4: alert("evaluated again");

I guess so, if that test is telling me what it seems...

oops: actually it does the same thing without a = 2;... looks like i need a better test!

08-27-2004, 09:34 AM
So it doesn't matter, because you have to use break; or else the case is not even checked, er something... (that's my scientific conclusion ;))... might as well do without the variable.

shoot, the manual did mention that (looking back...) & what a pointless question (yet again); but who knows... maybe one of these goose chases will lead to something worthwhile...
awe fooey! :o

08-27-2004, 01:55 PM
JavaScript is send-by-value - what this mean is that there is no difference between
switch(c) and
switch(a*b)from the switch statement's point of view. All expressions are evaluated before they are sent to the containing expression or statement.

08-28-2004, 09:47 AM
As opposed to send-by-ref. (correct?), whatever that actually means; and referenced values are ideal in loops...

08-28-2004, 01:23 PM
Actually it just struck me the reason is not at all that it's send-by-value. The reason is that it's eagerly evaluated instead of lazily evaluated.

In a way, you could say that in JavaScript, everything is evaluated from deepest nested to shallowest nested. This means that expressions are evaluated before they are sent to their surrounding expressions or statements, so the shallower statement or expression is never even aware that the value it's been sent was generated by evaluating something.

08-28-2004, 01:40 PM
Yeah, I noticed that... which makes it easy to string together compound references without needing a bunch of variables for each.
I really have no business sticking my nose behind the curtain, yet, anyway--but some ideas just never become clear until you can have a gaze at the whole picture...