Forums > Javascript

Switch statement

January 12, 2010 | 5:08 pm

Hello,

I begin to learn javascript but I’m blocked at switch statement. Could you tell me please what i made wrong

// inlets and outlets
inlets = 1;

outlets = 1;

// global variables
var x =0;

function msg_int (x)
{
y= x>2;
z= x<2;

switch (x)

{
case 2:
outlet(0,1);
post(1);
post();
break;

case y:
outlet(0,2);
post(2)
post();
break;

case z:
outlet(0,3);
post(3);
post();
break;
}

}


January 12, 2010 | 10:02 pm

You have a global variable called ‘x’ and also a local variable called ‘x’. The two are not the same. When your msg_int function is called, ‘x’ will always be the value sent in the inlet, therefore the only two possible results are that if you send it 2, then ‘case 2:’ will be executed, otherwise nothing will be executed.

Use a different variable name for the global x or the local x.


January 13, 2010 | 8:23 am

Sorry for my dumbness . I tried different possibilities and it didn’t work . Could you show me on example. Thanks

// inlets and outlets
inlets = 1;

outlets = 1;

// global variables
var x =0;

function msg_int (x)
{

var i ;
i=x;
y= i>2;
z=i<2;

switch (i)

{
case 2:
outlet(0,1);
post(1);
post();
break;

case y:
outlet(0,2);
post(2)
post();
break;

case z:
outlet(0,3);
post(3);
post();
break;

}

}


January 13, 2010 | 5:22 pm

I think you are probably better of with a plain old if…else, if I got the idea right I think this will do what you want.

// inlets and outlets
inlets = 1;
outlets = 1;

function msg_int(i)
 {

    if(i > 2){
        outlet(0, 2);
        post(2)
        post();
    }
    else if (i < 2){
        outlet(0, 3);
        post(3);
        post();
    }
    else{
        outlet(0, 1);
        post(1);
        post();
    };
}

January 13, 2010 | 5:32 pm

Yes with "else" and "if" I tried before and it is easier , but now i try to understand how "switch" works.

Basically If I send an int number to js if this number is 2 i want to receive via outlet the number 1, if the number is bigger than 2 i want 2, if is less i want 3.

thanks for the response


January 14, 2010 | 1:42 am

If you use switch the case needs to be something specific rather than a condition. In this instance you could either use if…else or some maths on the conditions themselves. To be honest the method below is messy and might be hard to figure out if you return to the code in the future, but it does work.

lh

outlet(0, (x==2) + (x>2)*2 + (x<2)*3 );


January 14, 2010 | 5:31 pm

merci bechamel and all javascript folks, It works very well,


January 14, 2010 | 7:41 pm

I tried to learn the loop statment .

The patch is

– Pasted Max Patch, click to expand. –

i use this java script

// inlets and outlets
inlets = 1;

outlets = 1;

// global variables
var x = 1

function msg_int (x)
{

var i;
if (x ===2){i=k;}

for (var k=1; k2){i= z;}
if(x


January 14, 2010 | 10:15 pm

You are trying to set the variable i to be the value of variable k which isn’t set to anything yet, it is "undefined". This will have no effect on the code below. If you want to loop only when the input is equal to 2 then put the for loop in the block following the if statement. Have a look at the javascript reference here for loads more information, it can be really helpful.

lh

function msg_int(x) {
    if (x==2) {
        for (var k=1; k<4; k++) {
            outlet(0,k);
        }
    }
}


January 14, 2010 | 11:36 pm

Hey,

There are a few problems with your code…

The first is, as Luke wrote, that you are assigning the undefined value of k to i, which is almost definitely not what you want.

The second problem is that if you want the loop to only execute if x==2, the loop itself must be inside the {} following the if statement.

The reason adding the two additional conditions seemed to fix your problem is that you introduced an error. When x isn’t 2, it tries to do "x = z". Since there is no z, the code stops and prints an error (look in your Max window). It never gets to the loop. When x is 2, this error doesn’t happen, and the loop executes.

The last problem isn’t really a problem, but is kind of strange. In what you posted, x===2 will work, but there are very few instances where it’s what you really want. I suggest you stick to == unless you have a specific reason why you want ===.

The code Luke posted is probably the "normal" way to do what you want, but the reason adding the other 2 if statements "fixed" it is subtle and I thought you could do with an explanation.

/brian


January 15, 2010 | 10:26 pm

Thank you guys, you illuminated me. Now I will learn the Array


January 16, 2010 | 1:26 am

This page is a good resource, the links at the top are also worth a look when you move on from arrays.

lh


January 16, 2010 | 8:49 am

Thanks Luke , It’s a very good resource. I will study today.


January 17, 2010 | 1:03 am

I’m not sure why you suggest using == over ===. Perhaps you have your terms reversed?

=== means "equal" (and !== means "not equal"). This is nearly always what you want.

== means "equal, using type coercion". This means that if the two arguments of a different type, Javascript will execute some rather obscure rules to make them the same type and then check for equality.

This has some undesirable consequences…

post(0 === '', 0 === '0', '' === '0', 'n');
post(0 == '', 0 == '0', '' == '0', 'n');

The first line prints 0 0 0 as expected (none of these are equal).

Astonishingly, the second line prints 1 1 0. So you can have x == y and y == z but x != z – mathematically, Javascript’s == is not "transitive". Very uncool.

Take-away from this: never, ever use == or != in Javascript; use === and !==. I can literally say that there isn’t one good reason to use == ("I’m sloppy and use strings and integers interchangeably" is a reason – but not a *good* reason. :-D)

(What’s REALLY annoying is that == is only a little smart…

var a = [1, 2, 3];
var b = [1, 2, 3];

post(a == b, a === b, '!', a, '!', b,  'n');

results in 0 0 ! 1 2 3 ! 1 2 3

So really – what’s the use?)


January 17, 2010 | 5:19 am

Regarding ===:

First of all, the nature of the "right way" to test for equality is an old argument. Common Lisp, for example, has 4 generic equality functions (eq, eql, equal and equalp), each of which is subtly different from the others (there’s also 5 type-specific equality functions). It’s still an argument worth having, however.

The JavaScript designers clearly intended for == to be the default, and === to be the special case. For one thing, they picked one of them to be ==, the standard equality operator in all the other C-derived languages. Also, the official Mozilla JavaScript documentation suggests it: "Use strict equality operators if the operands must be of a specific type as well as value or if the exact type of the operands is important. Otherwise, use the standard equality operators, which allow you to compare the identity of two operands even if they are not of the same type." This might be an artifact of JavaScript’s initial intended use as a browser scripting language, where easy conversion back and forth between textual and numerical types was highly desirable. And while the designer’s intent is obviously not the final word, it’s definitely worth considering.

I find that 99% of the time, JavaScript’s type coercion does what I want. In other words, the designer’s intent was correct. There are certainly gotchas like the one you pointed out, but there are always trade-offs when automation is in question.

I’d also point out that the other operators (like +) do similar types of coercion. There seems, therefore, to be an expectation in JavaScript that numbers and string-encoded numbers are interchangeable, like it or not. Sticking to that convention means no need to address a bug when someone else feeds your library a string-encoded number tomorrow, so there’s also an element of future-proofing.

You can certainly argue that avoiding the situation altogether and always being aware of what type your data is is the road to safer code, and I might be inclined to believe you. But unless you are the only one that uses your code, you may have a hard time remaining omniscient about how it is used.

I do agree that 0 == " is surprising. I was particularly surprised to learn that Number("") returns 0 while parseFloat("") returns NaN. So surprised that I checked the ECMAScript spec to make sure it was right! Thanks for pointing that out. Had I not run into this, I probably would have argued that the coercion rules are not really obscure (and they’re not, but the conversion rules are! Kind of a distinction without a difference). I wonder if it has anything to do with compatibility with C strings (in which 0 and the empty string really are the same thing).

Regarding it being only a ‘little’ smart: well, you’re trying to make it work for non-primitive data types. It doesn’t. That doesn’t bother me, partially because the assignment operator works differently for them also. There’s definitely a trade-off in having such a fundamental difference between data types without some sort of visual difference in the source code.

By the way, this distinction leads to a real example of == not being transitive:

var a = new String("foo");
var b = new String("foo");
a == "foo" => true
b == "foo" => true
a == b => false

How’s that for surprising? :)

To summarize: whether to use == or === by default is a personal preference. == is the standard to use by default. There are arguments for and against ==. I say that unless you have a specific reason to use === for the code you are writing, go with the standard.

/brian


January 17, 2010 | 8:59 pm

First off, aplogies to gobo. We’ve kind of taken over this thread with this discussion. That was not my intent when I made what I hadn’t thought would be a controversial comment.

I was interested to read Crockford’s comments on this, since he is probably more responsible for the salvation of JavaScript from its poor reputation than any other individual. His argument seems to basically boil down to an issue of type safety. He’s also consistent in his bias: he thinks that the coercion that comes along with + and other operators is a language design mistake.

To me, this fits in well with his overall modus operandi, which is to advocate certain patterns that make JavaScript the language that he would most want to use. And he’s certainly gotten pretty far with that.

Crockford also advocates a pattern that I whole-heartedly agree with, and mitigates a lot of the controversy: when you’re interested in the truthiness of a statement, don’t compare it, just test it. In other words, if(!x) rather than if(x == 0). If you really do want to compare against 0 (or '', undefined, null, false or true), you should probably be using ===.

I still like letting the language do the work for me. For example, I recently was doing some work with E4X, and found that == works pretty much exactly as I would expect.

I’ve found that the use of == as a default is far more controversial than I would have thought. So, while I’ll stick to my guns and continue to use == by default in my own code, and when I teach others, I certainly won’t again "correct" it in a beginner’s code.


January 18, 2010 | 7:18 am

No. is’s not a problem . I try to learn from what you say guys even many discussed things are nuances who are far away from me in this moment but it is stillinteresting


January 19, 2010 | 2:36 am

bgruber: excellent, very interesting post. And your non-transitivity example was eye-popping!

Re: Crockford – I also dislike the type coercion in + – it always bites me at some point when I try to add arrays together (in Python, that concatinates lists or tuples).

I agree with the if (!x) BUT I got burned with that quite a bit, again because of Python – in Python, ![] and !{} are true (empty lists), in JS they are false (an object that’s not null). At some point I had to look at every instance of ! in all my JS programs and check I was doing the right thing!

In fact, this whole thread boils down to craving Python. :-D If only, if only they’d chosen Python for the scripting language….

So much more rich libraries! So much better argument passing! Generators! (a minor language feature – except it’s so very useful for music). List comprehensions (ditto!)

I’ve used the Max py box pretty heavily, but Javascript lets you directly manipulate the Max objects – so I ended up with that.

At least we have Javascript which to my astonishment turned out to be an advanced language with lots of nice features like closures, a very light and interesting object model, and anonymous functions. (And, yes, Java, I’ve written Java for years but it’s so verbose I would be loathe to start development in it these days…)

Sorry for hijacking your thread, it’s a holiday!


Viewing 18 posts - 1 through 18 (of 18 total)