This is a list of 7 useful Javascript tips intended to improve your productivity and overall experience when using Javascript. These tips are for b...
For further actions, you may consider blocking this person and/or reporting abuse
Can you explain what makes a ternary operator better than an if-else statement?
And nesting them so the else is, itself, an ternary operator is making JavaScript be like the formula bar for Excel - unreadable. If I got a code review where someone had nested ternary operators, I'd fail it on readability and maintainability grounds. If it can't be easily followed by someone new to the code base, it's pointless.
The rest of the article is pretty useful, and reminded me of a couple of things which I haven't used for a while so forgotten about.
By default most linting rules will fail that nested ternary. That is just a terrible pattern. I don't get this current trend with avoiding else stemtements.
I think that ternary operator is good, but! not the nested one (spaghetti code...).
I usually use it when I whant to assign a value to a variable based on a criteria.
I agree with you. I just wanted to show that you could do an if, else if, and else with a ternary operator.
Thanks. It looked like you were encouraging people to do it.
I agree that ternary operators have their place, but nesting them in the real world (outside of excel or similar) is just madness
Hi Henry and thanks for your article full of interesting advices!
When it comes to printing to the console by a predicate, I like to use one console and use the ternary operator inside the method call.
This shorten the code a little bit more, while still keeping the conditional rendering of those strings.
Great point! This way definitely is more concise and readable.
Great tips for someone just getting started and mostly relevant to other languages not just JS!
One thing I would suggest not to use is the nested ternary operators as that really hurts readability - got to remember that as developers we should be optimising mostly for other humans to be able to read our code, not simply machines (or we would write 1s and 0s directly, right!)
Maybe another option would be to put the second ternary inside a temp variable on a separate line, e.g:
‘’’
const x = 10;
const notTen = x === 9 ?
“x is 9” :
“x is not 10”;
const logStmt = x === 10 ?
"x is 10" :
notTen;
console.log(logStmt);
‘’’
(Apologies for formatting, typing on mobile!)
Great tips! I agree that the nested ternary operators are confusing but I just wanted to show that an if, else if, and else statement is possible with ternary operators. The way you did it is much cleaner.
This is excellent.
Thanks!