Search code examples
javascriptoopconditional-operatorthrow

Throw error message doesn't compile on OOP Javascript ternary operators


Why does this way it compiles:

this.setAlunos = function(alunos){
    if(this.getTurma() > 0){
        this.alunos = alunos.split(",");
    }
    else{
        throw "you must set a 'turma' before inserting students on it";
    }
};

And this does not?

this.setAlunos = function(alunos){
    this.getTurma() > 0 ? this.alunos = alunos.split(",") : throw "you must set a 'turma' before inserting students on it";
};

Solution

  • You can't actually throw an error directly inside a ternary operator, like you're trying to do there. You can, however, wrap the throw in an anonymous function, like this:

    this.setAlunos = function(alunos){
        this.getTurma() > 0 ? this.alunos = alunos.split(",") : (function(){throw "you must set a 'turma' before inserting students on it"}());
    };
    

    Then it will work properly. However, just because you can do something doesn't mean you should. I recommend leaving your code as it was before, as it's much more readable.