0
Q: Ternary Operators js 👈
Hello!!! I'm looking for a way (if it's posible) to write this with ternary operators ```js var age = "" if (age < 0) { alert("you are not born yet"); if (age == "") { alert("Error"); } } else if (age < 18) { alert("You are a minor"); ```
7 Respuestas
+ 3
Some programmers think over use of the Ternary operator makes the code look sloppy or hard to read. But personally I prefer that than a bunch of if.. else statements.
+ 3
Here's my example based on your initial if else statements.
var age = "";
var ageResult = age <= 0 ? "you are not born yet"
: age <= 18 ? "Your are a minor"
: age == 100 ? "Error"
//else is the last statement :
: "You are an adult"
console.log(` ${ageResult}`);
+ 2
Chris Coder
Nice example of Ternery Operators.
I thought you could only use it to replace a simple if/else scenario, but your example provides clean flexibility
+ 1
What have you tried?
+ 1
Call it like this
console(`You are ${ageResult}`);
0
Check <age> == "" before checking <age> < 0. It doesn't make much sense to test <age> against number and string in the same conditional block.
0
well I already found how to do it, here is an example
```
const age = -1;
const ageResult =
age < 0
? (console.log("❌"), "Error😿")
: "You were born";
console.log(ageResult);
//logs Error😿
//but first runs the console.log("❌")
```
But someone told me I was denaturalizing the language doing that, is it that bad?