+ 6

Can we say conditional operators of JavaScript is similar to that of if operator in python?

2nd Sep 2019, 2:12 AM
Avinash
Avinash - avatar
3 Answers
+ 7
Jay Matthews I just recently realized Python has a ternary like operator and hate it. đŸ€Ł I imagine it would be more readable for those who haven't actively worked in any of the 37 or so languages I've reviewed that follow the sequence listed below: ---- x = (condition) | if_true | if_false ---- Aside from Python, only APL and Common Lisp supports the sequence: ---- x = if_true | (condition) | if_false ---- The other challenge for me getting used to the Python approach is multiline ternaries look similar to the standard if else block that they can be difficult to differentiate. Example: (Python) ---- #1 Standard If Else: ---- if itemA == itemB: newItemVariable = itemB else: newItemVariable = itemA ---- #2 Ternary Single Line: ---- newItemVariable = itemB if itemA == itemB else itemA ---- #3 Ternary Multi Line: ---- newItemVariable = itemB \ if itemA == itemB \ else itemA #1 and #3 has already tripped me up as I'm reviewing my own code. đŸ€Šâ€â™‚ïž
2nd Sep 2019, 4:33 AM
David Carroll
David Carroll - avatar
+ 5
Pretty much all programming languages have conditional statements and if statements are the most basic of these.
2nd Sep 2019, 2:36 AM
Sonic
Sonic - avatar
+ 3
Example: (Javascript) ---- #1 Standard If Else: ---- if(itemA == itemB) newItemVariable = itemB else newItemVariable = itemA ---- #2 Ternary Single Line: ---- newItemVariable = itemA == itemB ? itemB : itemA ---- #3 Ternary Multi Line: ---- newItemVariable = itemA == itemB ? itemB : itemA There is absolutely no way anyone would confuse #1 and #3 from being the same thing in other languages. Finding bugs with invalid conditions will be relatively easier to spot when the mind doesn't have to context switch between the location of the conditional expression depending on using #1 or #3 in the Python example. As someone who does a lot of code reviews, I've never had to adjust my mind for something like this within the same language, or even across multiple languages. I'm just saying. 😉
2nd Sep 2019, 4:43 AM
David Carroll
David Carroll - avatar