1
I want you to get the selectedGenre
is different from empty or null
he perform movie.genre === selectedGenre
, but if it is null or empty just exit the function without returning anything.
selectedGenre ? movie.genre === selectedGenre :
1
I want you to get the selectedGenre
is different from empty or null
he perform movie.genre === selectedGenre
, but if it is null or empty just exit the function without returning anything.
selectedGenre ? movie.genre === selectedGenre :
3
Not making a ternary, this operator was created to give a result, if you do not want a result to be made the operator should not be used, clearly it is a case for a if
.
But if I want to insist on it too much, what I reinforce is a mistake can result in null and void:
false ? console.log("ok") : null;
But there’s no way to make a function shut down without doing a bigger scam.
Correct and shorter form:
if (false) console.log("ok");
And using function to give output:
function teste(valor) {
if (valor) console.log("ok");
else return;
console.log("continuou");
}
teste(false);
I put in the Github for future reference.
When you want to control the execution flow if
is correct. Operators serve to generate results, not control flow.
2
In Javascript there is no type void
, then the function, explicitly or not, will return something, if not specified, will be undefined
:
function example() {}
console.log(example());
function example2() { return; }
console.log(example2());
const example3 = () => {};
console.log(example3());
Then you can return undefined
in the third working of the ternary ("else
"):
function example(bool) {
return bool ? 'anything' : undefined;
}
console.log(example(true), example(false));
const example2 = (bool) => bool ? 'anything' : undefined;
console.log(example2(true), example2(false));
Another way to get the Undefined value is by using the operator void
:
function example(bool) {
return bool ? 'anything' : void 0;
}
console.log(example(true), example(false));
const example2 = (bool) => bool ? 'anything' : void 0;
console.log(example2(true), example2(false));
Still, I agree with the previous answer, the if
is better for this purpose, however, in case of Arrow functions with a single line, in order to maintain simplicity, makes sense and is acceptable its use
Browser other questions tagged javascript operators
You are not signed in. Login or sign up in order to post.
Ternary operator should not be used as flow control.
– Augusto Vasques
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site
– Maniero