Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Is the switch expression evaluated only once?

1. ## Is the switch expression evaluated only once?

If you compare:

switch(a * b){...}

to:

var expression = a * b;
switch(expression){...}

does storing 'expression' serve any purpose?

• function foo()
{
var a = 1;
var b = 2;
switch(a * b)
{
case 2: alert("evaluated once");a = 2;
}
}

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

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

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

[slapMe]
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!
[/slapMe]

• JavaScript is send-by-value - what this mean is that there is no difference between
Code:
```var
c=a*b;
switch(c)```
and
Code:
`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.

• As opposed to send-by-ref. (correct?), whatever that actually means; and referenced values are ideal in loops...

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

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

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•