Ternary operator - continue statement


I was wondering why a ternary operator can’t take a continue statement?

/* for (let i = 0; i < 3; i++) { i !== 1 ? console.log(i) : continue; } */ //SyntaxError: Unexpected keyword 'continue' for (let j = 0; j < 3; j++) { if (j !== 1) { console.log(j) } else { continue; } } //prints 0 // 2

Thank you,

The ternary expects 2 expressions. Expressions in JS return a value (which could be undefined - which is what is returned from your console.log). continue is not an expression but a statement (which does not return anything). Other statements would give similar error in the ternary (such as declaring a variable with let). This is one reason to not rely excessively on the ternary to replace if/else logic.

Good brief summary of expression vs statement: Javascript: difference between a statement and an expression? - Stack Overflow


Thank you kind stranger.

1 Like