Search code examples
javascriptif-statementconditional-operator

Breaking a while loop with a ternary operator (one line if else)


i would like to break a while loop with inside ternary operator.

Example:

while (true){ onderwerpenArray.includes(temp) ? onderwerpenArray.splice(onderwerpenArray.indexOf(temp), 1) : break;}

But i get a message saying expresion expected

I would like to know if this is possible and how.
otherwise if you know a different way to make it as compact as this i would like to know as well.


Solution

  • break is not an expression so it cannot be used in that context. However, you can directly put onderwerpenArray.includes(temp) in the loop condition:

    while (onderwerpenArray.includes(temp)) 
        onderwerpenArray.splice(onderwerpenArray.indexOf(temp), 1);
    

    To remove all occurrences of temp in onderwerpenArray, it is simpler to use Array#filter.

    onderwerpenArray = onderwerpenArray.filter(x => x !== temp);