DEV Community

Discussion on: Writing If Statements with the Ternary Operator

Collapse
 
jingxue profile image
Jing Xue

You might want to use a different example where the variable is of a different type than boolean, e.g.:

let msg = (userId.value.length === 10) ? 'length 10' : 'other length'

Because if the variable itself is a boolean, why not just say:

let userIdValid = userId.value.length === 10
Collapse
 
valentinaperic profile image
Valentina Peric

Yes, you could remove the operand altogether if you wanted to further refactor and simplify the code! This is great. I wanted to show an example that was explicit in the truthy expression and falsy expression. Thanks for the input, Jing 🙂

Collapse
 
leob profile image
leob • Edited

I agree that the original example (evaluating to true or false) was slightly redundant ... and a bit of a tangential rant: the brackets "()" are redundant as well - the following works fine too:

let msg = userId.value.length === 10 ? 'length 10' : 'other length';

In the past I often worked with people who wrote huge amounts of unnecessary brackets in their expressions, and it always irked me - when I see stuff like this:

if (((a*b)+1) > (c-(d/e))) {

then I can't help myself and I have to immediately change it to:

if (a*b + 1 > c - d/e) {

which means exactly the same thing (because of the priority rules that everyone should have learned somewhere in the 6th grade of primary school). Reads so much better ...