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"); ```

22nd Jun 2022, 1:51 AM
Jace🎭
Jace🎭 - avatar
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.
22nd Jun 2022, 3:08 AM
Chris Coder
Chris Coder - avatar
+ 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}`);
22nd Jun 2022, 3:16 AM
Chris Coder
Chris Coder - avatar
+ 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
22nd Jun 2022, 3:51 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
What have you tried?
22nd Jun 2022, 2:38 AM
Chris Coder
Chris Coder - avatar
+ 1
Call it like this console(`You are ${ageResult}`);
22nd Jun 2022, 3:04 AM
Chris Coder
Chris Coder - avatar
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.
22nd Jun 2022, 2:39 AM
Ipang
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?
22nd Jun 2022, 2:57 AM
Jace🎭
Jace🎭 - avatar