0

I've just picked up the concept of a ternary statement, and tried to use it in place of an if / else if / else statement that I'm familiar with. But the code seems to have a syntax error. What is a ternary statement unable to do that an if statement can do? I wonder if ternary statements are more appropriate for executing simple commands.


The 'bin' array is a collection of sub-arrays, consisting of items discarded from the 'inventory' array, courtesy of the splice and push methods.


var bin = [ ['Orichalcum'], ['Rapier', 'Panacea'], ['Bow'], ['Antidote', 'Cheese', 'Whip'],  
['Elixir', 'Herb'], ['Timbrel', 'Dagger', 'Boomerang'] ];


var message = (! bin.length) ?

     'No items have been removed.'

    : (bin.length === 1) ?

         bin[0].length + ' items have been removed.'

        : (
            for (var i = 1; i < bin.length; i++) {
                for (var j = 0; j < bin[i].length; j++) {
                    bin[0].push(bin[i][j]);
                }
            },

            bin[0].length + ' items have been removed.'
        );


alert(message);
Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
  • 4
    do **NOT** abuse the ternary like that. it's disgustingly ugly code. nesting ternaries transcends "abuse" into "justification for genocide" – Marc B Dec 15 '15 at 19:06
  • Related: http://stackoverflow.com/questions/34292255/short-circuit-with-a-return-statement – Sebastian Simon Dec 15 '15 at 19:06
  • 2
    The real question here might be why do this? It's extremely difficult to read as compared to an `if. . . else` statement. Further you haven't indicated what is and is not working, what output are you receiving, what output do you expect? – CollinD Dec 15 '15 at 19:07
  • If there is actually a good reason to use a ternary statement, such as when a decision is made that results in one of only two possible outcomes, then the ternary statement is fine. Remember that microptimizations like this, don't buy you any benefit. It's better to program for readability and let the run-time engine and third-party tools, like bundlers and minifers do the "extra" optimizations for you. In short, ***don't*** use a ternary operator like this. – War10ck Dec 15 '15 at 19:07
  • 3
    Code like this is why we can't have nice things any more. – James Gaunt Dec 15 '15 at 19:08
  • 1
    Just a note, please use block quotes when quoting from a source. – Spencer Wieczorek Dec 15 '15 at 19:09
  • What @War10ck said. It's a useful tool, but just because you learn that you can use a wrench to hit a nail into a wall and sometimes it's quicker, doesn't mean you shouldn't mostly use a hammer. – zfrisch Dec 15 '15 at 19:10
  • You could use ES7 array comprehensions with ternary statements, theoretically. – Sebastian Simon Dec 15 '15 at 19:10

1 Answers1

3

The ? : operator is an expression, not a statement. This means you cannot nest other statements (such as for) inside it.

Jonas Høgh
  • 10,358
  • 1
  • 26
  • 46