Search code examples
javascriptternary

i++ doesn't work in ternary statement


Can someone explain to me why this statement won't work?

i = (i >= 8 ? 1 : i++);

yet this one does?

i = (i >= 8 ? 1 : (i + 1));


Solution

  • As Raymond mentioned, you're using postincrement, you should use preincrement in this context:

    i = (i >= 8 ? 1 : ++i);