Google Translate

English French German Spain Italian Dutch Russian Portuguese Japanese Korean Arabic Chinese Simplified by : BTF, ed. by JRD (me!)

mercoledì 18 agosto 2010

Using javascript's ternary operator with multiple statements or commands

Today I made a new discovery in javascript that does not seem to be very well documented. Maybe it's so obvious that it's given for granted. Well I'm self-taught so I can't take anything for granted. My discovery has to do with the use of the ternary operator, a kind of shortcut for conditional statements, with multiple statements. The ternary operator is a compact way of writing conditional statements, instead of writing out fully an "if...then...else" statement, that is "if (condition) { statements; } else { statements; }", you just write  "(condition) ? statement : statement;", which corresponds like this: "(if) ? then : else;". Now I was trying to use the ternary operatore but I needed to give multiple statements or commands in case of a postive result. And in javascript multiple statements should be separated by a semicolon, but a semicolon in the middle of a ternary operator will interrupt it. Well I found a solution: you just have to chain the statements or commands with a plus sign "+". Maybe some people already know that, I didn't. Here are some examples that illustrate concretely these usages.

Example of a conditional statement with a single command:

if(1==1) { alert("Hello") }
else { alert("Goodbye") }

Example of a conditional statement with multiple commands:

if(1==1) { alert("Hello"); alert("World!"); }
else { alert("Goodbye"); alert("Sky!"); }

Example of a ternary operator with a single command:

(1==1) ? alert("Hello") : alert("Goodbye");

Example of a ternary operator with multiple commands separated by a semicolon:

(1==1) ? alert("Hello"); alert("World!"); : alert("Goodbye"); alert("Sky!");

This form is not correct because the semicolon within the ternary operator will interrupt it.

Instead in this way it is possible to have multiple commands in the ternary operator:

Example of a ternary operator with multiple commands chained by a plus sign "+":

(1==1) ? alert("Hello")+alert("World!") : alert("Goodbye")+alert("Sky!");

I had no problems with this method, I've tried in a couple of circumstances and it's worked great.