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);
8
  • 4
    do NOT abuse the ternary like that. it's disgustingly ugly code. nesting ternaries transcends "abuse" into "justification for genocide" Commented Dec 15, 2015 at 19:06
  • Related: stackoverflow.com/questions/34292255/… Commented Dec 15, 2015 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? Commented Dec 15, 2015 at 19:07
  • 3
    Code like this is why we can't have nice things any more. Commented Dec 15, 2015 at 19:08
  • 1
    Just a note, please use block quotes when quoting from a source. Commented Dec 15, 2015 at 19:09

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.