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 however would not be correct, and just won’t work, because the semicolon within the ternary operator will interrupt it. It is however 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.

Be First to Comment

Lascia un commento

Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.