My rule of thumb is that if you go beyond one level of nested ternaries them you need a function.
@Asto50811 ай бұрын
Exactly. Ternary is for replacing a single if-else statement. Nothing more
@MariusEidem11 ай бұрын
or a switch
@ewertonls_11 ай бұрын
the perfect count of ternaries is between 0 and 0
@p_o_z_e11 ай бұрын
ya, this is what i have done aswell.
@lukasmolcic514311 ай бұрын
I like to have this as a linter rule as well
@asdqwe442711 ай бұрын
Formatting nested ternary statements is a wild concept to me. Never solve problems that you don’t need to have. Outlaw nested ternary statements!
@dovos857211 ай бұрын
yeah they lost their purpose if you need to multiline them.
@Mystic99811 ай бұрын
Prettier is a code formatter,. It's there to make your bad ideas look neat, not point them out.
@asdqwe442711 ай бұрын
@@Mystic998 sure, but you can still limit what type of problems you take on. I wouldn’t have spent a second on it
@ChillAutos10 ай бұрын
@@asdqwe4427I guess you’ve never written a complex typescript type. It solves a real problem, just not one you have.
@UnwittingSweater11 ай бұрын
Another plus for vertical code is GIT understands the changes better.
@connorskudlarek859811 ай бұрын
git diff "Wait, why did this line get removed? Oh... it didn't, they just renamed one of the variables."
@Kane012311 ай бұрын
Facts
@steamer2k31911 ай бұрын
It requires multiple times more cognitive power for humans to work through two dimensions instead of one. For the one dimension, work with the grain of the scroll wheel. Write vertical code. Maybe somewhat less applicable today but try to keep it from going much past 80 columns wide in case you ever need to maintain the code from a tiny laptop and/or SSH situation. (80 because the old teletype hardware was 80x24 and many terminal emulators still default that way)
@SoreBrain11 ай бұрын
The fact prime had to triple check if the logic is the same, demonstrates why no one likes reading them
@felixjohnson387411 ай бұрын
*_cough cough skill issue cough_*
@Nootlink11 ай бұрын
@@felixjohnson3874it's not really a skill issue if you are reading clusterfuck of code
@marcoshalberstadt764611 ай бұрын
@@felixjohnson3874 Indeed, it's the kind of skill that reasonable people _should_ have issues with.
@berrywarmer1111 ай бұрын
Forreal. Truly professional developers understand that the best code quality is whatever is easiest for their coworkers both now and five years from now will understand. In both cases, an "if" statement is that boring easy answer that the ternary trend setters refuse to use.
@andreaswenzel308911 ай бұрын
Hol' up. If the thing can't bark, but can meow and is scary then it's a cat in the first one but a wolf in the 2nd... isn't it?
@danielgrenehed290411 ай бұрын
The logic is not the same in the ternaries, since in the second example all scary animals would return 'wolf' regardless of if it could bark or not. Considering the case when there are only wolfs, dogs, cats and bunnies the result would be the same, but as soon as you add another scary animal the second example would have to be rewritten. Either way, I probably add species to the pet instead of the ternary, I never nest ternaries.
@EmitAshborn11 ай бұрын
Isn't it different with only the animals given as well? The top one requires wolf to bark and be scary, the bottom only requires scary.
@Exilum11 ай бұрын
It's crazy how consistent Prime is in his statements. The 80-lines talk was almost the exact same as every single previous time.
@BosonCollider11 ай бұрын
I the words of theo, he is a superdeterministic mf
@ZodakZach11 ай бұрын
i’m starting to think he created an AI version of himself
@Hellbending11 ай бұрын
Welcome to adhd life my bro 😂 Mans set it upppp and ingrained it and that’s how it’s understood and lockeddd in. Reason that conceptual code things stick really hard after we understand them 💪
@apollolux11 ай бұрын
Consistency of belief happens when someone is genuine and honest about a thing.
@Exilum11 ай бұрын
@@apollolux It's not that simple. People often change the way they talk about something. People can also change opinions, or feel slightly differently about something depending on the context or how their day went. You can be genuine and not be pseudo-random like prime. Given a seed, you always get the same output.
@vitiok7811 ай бұрын
A long time ago I wanted to write some frontend stuff. And when I saw those nested ternaries in React I switched to Vue immediately.
@FunkyELF11 ай бұрын
My main use for ternaries is when your logic needs to fit within a single expression... Like a C macro (I know these are out of style and considered bad)... Or a Python lambda (anonymous function) or Python comprehension. Here the alternative is making it a function, but then you have to deal with naming it.
@VelvetSage11 ай бұрын
in js you can just make an IIFE
@sinom11 ай бұрын
Lambdas exist in javascript as well so you don't need to name them. And IIFE is just a lambda which you immediately call
@steamer2k31911 ай бұрын
Yeah some languages don't work well unless you use ternaries 😡. In Terraform/HCL, the && operator doesn't short-circuit so there are some places you have to use ternaries. In Dart/Flutter, if/else blocks aren't expressions so the syntax gets a little ugly when you want to conditionally render a widget. Ternaries are one alternative
@RandomGeometryDashStuff11 ай бұрын
@@VelvetSageassuming iife is (function(){})() doesn't that create a function object and use extra call stack?
@VelvetSage11 ай бұрын
@@RandomGeometryDashStuff it does
@spamviking859111 ай бұрын
If it’s just var = (cond) ? 1 : 2; they’re fine. If you’re nesting them, you dun goofed.
@АндрейБыканутый11 ай бұрын
Amen!
@haulin11 ай бұрын
The reason why formatting of nested ternaries needs to be solved is TypeScript's conditional types. There is no if/else and they are as unreadable as you'd expect. I hope TS itself comes with an alternative, but if not, we need nested ternaries in frontend.
@Rohinthas11 ай бұрын
THANK YOU! I was just wondering why nested ternaries exist in the first place
@Reichstaubenminister11 ай бұрын
@@RohinthasThere's no way for them not to without imposing an arbitrary limit. It's just an expression after all.
@normalmighty11 ай бұрын
Exactly! There's another discussion to be had about potentially adding alternatives to ternaries in places like typescript types, but that's well and truly out of the control of the team at Prettier. They're doing a good job of dealing with the reality that you have no choice but to nest ternaries in a lot of cases
@TheNewton11 ай бұрын
and if that's the reason then it should only be targeting advanced typescript users. And doesn't that make the example weirdly superfluous because it's doing string based type checking/output through object properties which you shouldn't have to do in typescript, ffs TYPE is in the bloody language name.
@PointOneX11 ай бұрын
Exactly this. We have a lint rule banning nested ternary and I’m pretty content with that. I think IIFEs are great and make ternaries in JS pretty pointless. However, you have to use them for conditional types which are super useful for maintaining strong typing while still taking advantage of the dynamic nature of JavaScript. Ban nested ternary and turn this rule on anyway to fix TS conditional types.
@genghisdingus10 ай бұрын
Ternaries are basically if you want to make a super small basic if statement Example: var value; if(thingy.do()) { value = "nice"; } else { value = "bad"; } --- vs --- var value = thingy.do() ? "nice" : "bad"; Trying to nest ternaries is a bad idea because you're basically just making less readable if statements at that point.
@BigBahss11 ай бұрын
Ternaries are great. Single ternaries that is. As soon as you've nested a single ternary, you should just be using an if statement
@hobster0711 ай бұрын
Same here. if I need to go more that a single ternary just go with if. No need to complicate
@theodorealenas317111 ай бұрын
Single and shorter than 50 characters total, that would be my version. Chasing colons is like chacing bugs.
@BigBahss11 ай бұрын
@@theodorealenas3171 Fair, though a decent formatter typically makes the question marks and colons easy to see
@theodorealenas317111 ай бұрын
@@BigBahss Okay, maybe we have a different background. I haven't worked yet and the only time I saw ternaries and had to understand them, was from a front end guy, and we collaborated in a Uni project (I haven't worked yet). That was 10 lines between question mark and colon, and then another many lines after the colon. So that's what I have on my mind. Even if the bits were highlighted with a laser in my eye, they'd still be a pain. But 2-3 lines would be fair I suppose, with some formatting styles.
@hentype2 ай бұрын
yeah, the moment ternaries become less readable is when they defeat their own purpose.
@Tony-dp1rl11 ай бұрын
Even if those methods were dynamic, and results changed at runtime, I would still prefer something like this to nested ternaries. function getAnimalName(pet) { if (pet.canSqueak()) return "mouse"; if (pet.canMeow()) return "cat"; if (pet.canBark()) return pet.isScary() ? "wolf" : "dog"; return "possibly a bunny"; }
@connorskudlarek859811 ай бұрын
This is the way. Just use a function. May want to pass in an object that holds all the pets though. Something like: "function getAnimalName(pet, allKnownPets){/*loop over object of known pets*/} After like 20 possible pets, you're strongly coupling your pets data to your pet identifying function. Even 5 would be above my comfort level, but might make sense if coupling them is important to the maintenance of the app.
@sillysquirrel997911 ай бұрын
THIS! Just remove unnesessary elses make 100x ez to understand logic
@TheNewton11 ай бұрын
as long as you can use if-else, apparently a reason for this is typescript conditional-types needing to be used with ternaries.
@connorskudlarek859811 ай бұрын
@@anon_y_mousse I'm not really sure what you mean here. The function is being used to identify the animal name by calling all possible methods, isn't it? Not sure where sorting the pets came from either. We're basically inferring description data about the object by calling a public method we don't know exists until it runs. You have the pet object, but you don't know what it is in this contrived example. You can find out by identifying through methods it 'might' have (bark(), squeak(), scary(), etc). That is the point of these ternaries, it figures out what the animal is by testing if the method that is unique to that animal returns a truthy value. If it does, then it is the return value of that ternary. I don't really know how you could turn a ternary check like this into a hashmap. It isn't calling pet.name() where the return value of pet.name() is being looked up in a list to see if it exists in the list. If that were the case, then you would certainly save time by hashmap (although you'll lose space). There is certainly faster ways to find out if a function exists on an object, and a "pet.name" attribute would certainly be a lot faster than identifying it through a method call... but the contrived example is limiting us to actually run the function. It is a perfect opportunity to split this into parallel processing though. Whereas nested ternary will lock it to single-threaded checks.
@Chamieiniibet11 ай бұрын
Next we have a squeaky rat that is scary and a meowing scary non-cat, and you end up with a 20-lines monster of if-else.
@Ardren11 ай бұрын
The only way to make nested ternaries pretty is to turn them into if-else blocks. Insane to be wasting time on this.
@Asto50811 ай бұрын
switch-case without fallthrough much more readable actually
@_jovian11 ай бұрын
If we're talking js/ts I'm a fan of switch Switch(true){ case [condition]: do something
@dirkbester905011 ай бұрын
Yes! I hard no nested ternaries . A single ternary has to be physically short so that it is comprehensible. No taking up the entire line, it has to actually be 1/2 a line or less and use single variables for both cases and fairly simple in the if. I want to read code, not sit there and puzzle it out.
@shioli392711 ай бұрын
Yeah, I´d also think so too. But for prettier it is probably the correct solution to figure out how to format anything 'properly'. "Don´t do this write if/else instead" would be the job of a linter. You would not expect prettier to format away 'as any' either.
@Rohinthas11 ай бұрын
Hard agree, I can accept a ternary if its usage can be fit into one line, that is, when even writing the if-else block feels like its wasting space. For everything else its just a less readable version of if-else and switch. I get that Prettier needs to account for people using it in this terrible way, but man does it feel like wasted time.
@Exilum11 ай бұрын
On ternary statements, I like them when there's only one level. Nested ternary statements are a bit too messy, so I tend to make a function. But if there's maybe only 2 levels and it's something short I find easy to read, I can use one.
@josefpharma471410 ай бұрын
Totally agree. I never used a nested one in the last 10 years. (Not in C++, not in Java, not in C#, not in typescript). Nobody in the teams I worked with, used them as well. IMHO: It would not pass code review 😀
@aleksd28611 ай бұрын
10:40 it’s showcasing different things. Before wolf had to be scary and bark but now can only be scary
@awesomedavid201211 ай бұрын
I think very simple ternaries are good. I find taking 5 lines to write 1 line is very annoying and harder to read. Yes, it can be abused. But so can any other syntax. Consider functions with 15 arguments. Just because it can be misused doesn't mean we disallow it (*cough* Go *cough*)
@MenkoDany11 ай бұрын
// class Player { // constructor playerHP = isHardDifficulty ? 80 : 100;
@awesomedavid201211 ай бұрын
@@MenkoDanyexactly. I think that's totally valid and more readable than taking more lines.
@miklow660511 ай бұрын
@@MenkoDany ifelse( isHardDifficulty, 80, 100 )
@Asto50811 ай бұрын
@@miklow6605Ugly. It's kinda like doing add(3,add(1,2)) instead of 1+2+3
@totalermist11 ай бұрын
The problem is that if-conditionals aren't expressions. A ternary is a crutch to turn a construct that's a statement into an expression. This issue prevents perfectly sound code like "const x = a if cond else b" from being expressed, as they force you to separate declaration from initialisation and even lose the const qualifier entirely without ternaries.
@quelchx11 ай бұрын
Love reading a good ternary statement with nested ternary statements.
@soyitiel11 ай бұрын
Yes. #TeamTernary here too. For instance, if-else staments in Rust could be considered as ternary statements with extra syntax (syntactic acid, maybe, as opposed to syntactic sugar?) This example can be found in the Rust docs: let y = if 12 * 15 > 150 { "Bigger" } else { "Smaller" }; Which, with a tiny adjusment and a bit of squinting, starts to look a lot like a ternary statement let y = if 12 * 15 > 150 { "Bigger" } else { "Smaller" };
@jongeduard11 ай бұрын
In C# when writing ternaries, I place both the question mark and the colon at the start of the next line (and indent these), so that they are easy to recognize, like I do with most operator symbols these days. In the past I have written much more operators in a trailing way, but I discovered that I don't like it, especially when lines become longer. But for really short ternary code lines with very simple values, I am not using multiple lines at all. When everything is super easy to read on the same line. However, it's still always good to ask yourself what code construct you use of course. The example in the video is exactly such a situation where you cannot use a switch or match expression, because your input are many different values from different methods. But when you can, it's obviously the preferred way for such more complex code. What I like in Rust though, is that you can have multiple statements inside a match arm, while returning a value just from final expression after these preceding statements. In C# I mis that a bit, when you need to write multiple lines, you really have to fall back to the old school C and C++ like switch statement which does not work like an expression and returns no value. And Rust has also no specific syntax ternary operator, but just uses if else which are value returning expressions too. But actually I still mis the C style ternary operator a bit to be honest, because for simple things it's still more concise.
@kazaakas11 ай бұрын
Same. I believe it's due to whether you prefer a functional style. I don't want to clog up my namespace with lots of small functions that I only need once, and I don't want to avoid mutability. Ternaries are a perfect solution for that.
@mudscuffer11 ай бұрын
10:49 the ternaries are not the same. In the first code snippet an animal that "is scary" but "can't bark" is "probably a bunny", not a wolf.
@sasukesarutobi386211 ай бұрын
And that's why I don't like nested conditionals, ternary or not. Like Brian Kernighan says: "Debugging is twice as hard as writing the code in the first place, so if you write the code as cleverly as possible, you will not be smart enough to debug it."
@ja31ya11 ай бұрын
It's obvious that "scary" wouldn't apply to a bunny, so actually the first snippet is being corrected by the second. "scary" is only applicable to the wolf, so there's no reason to check if it can bark. Of course I'm not sure if that was the intention of the example...cause you're correct, the outcomes are different, but the second one is a far more intuitive outcome, given the context.
@notlekrut11 ай бұрын
Also love the fact that they had to change the order of the ternaries (it now immediately returns wolf without even checking if it barks unlike the first code!), further showcasing how dumb it is to even do nested ternaries in the first place.
@notlekrut11 ай бұрын
@@ja31ya That's only true with the given set of animals. Hell, the examples are still wrong, the first code only returns wolf if the animal canBark and isScary. But the second code immediately returns wolf if it's scary. That's clearly wrong, given the conditions of the first code and the moment you add any other animal it could easily break the whole chain and you'll have to rewrite it
@ja31ya11 ай бұрын
Keep in mind that they admit it's a "contrived" example, which means it's less about the logic and more a demonstration of aesthetics. We could go back and forth all day about what the intent of the code is, but ultimately it's irrelevant in the context of the article.@@notlekrut
@Reydriel11 ай бұрын
let x = if *conditional* { *expression1* } else { *expression2* }; Hooray for expression languages, where ternaries are just normal if-statements lol
@Asto50811 ай бұрын
compared with let x = conditional ? expression1: expression2 you have much more clutter, especially if you format this with { foo } style Instead of 1 line, you have 10+ lines, depending on the language and style. Ternary is useful for replacing these kind of singular if-else blocks
@tiranito283411 ай бұрын
@@Asto508 Yeah, I agree with that, tho I also think it would be nice if more languages were to treat if statements as expressions that can be evaluated. Then you could also write it the same way the other user proposed, which is a really nice notation if you want to include more code to be executed within the code block, in my opinion at least. x = cond ? val1 : val2; is nice for 1 single condition. But if you have multiple conditions, even if it is possible to nest the ternaries, it eventually becomes better to just write something like an if else chain or a switch depending on the case and language... but sometimes it would be pretty cool if you could just write: x = if cond1 { do_something1(); val1; } else if (cond2) { do_something2(); val2; } else { do_something3(); val3; } or something like that. If I recall correctly, Jai does something similar, as well as allowing ifs without parenthesis. At first it looks weird, but it feels like a far more flexible system where you can actually assign ifs as expressions, cause then you can get the same behavior of a ternary but with as many conditions as you want. Tho I guess with ternary notation you can always write something like this: x = cond1 ? val1 : cond2 ? val2 : cond3 ? val3 : val4 which aint that bad if you think about it. The only problem is if you want to have more logic within some of the blocks. It then would pretty much become a situation where you have to remember to assign x within all conditional blocks. The only use of having something like this might be to give some kind of compile time error if you are assigning x but you forgot to write a value at the end of the code block in all conditional statements. Tho, in C, you can do the following: x = cond1 ? do_something1(), val1 : cond2 ? do_something2(), val2 : cond3 ? val3 : val4 which will evaluate each condition to the value at the end of the comma separated list of statements (which can also go in parenthesis and be treated as a single expression). But the problem with that way of doing things is that you can't have variables that are local to each conditional block, or function calls that interact with eachother, similar to how a non block guarded switch case statement works in C. Personally, I think that the only use in allowing the if-expressions would be if you could contain other operations within the code block, but only evaluating the block to the last expression within the block, kinda like how the GNU C expression statements compiler extension works. For example, that problem I mentioned before could be fixed with the GNU extension as follows: x = cond1 ? ({ some_local_var = do_something1(); val1 * some_local_var;}): cond2 ? val2: cond3 ? val3 : val4 In short, I don't think that the ternary notation is as bad as people make it out to be. It's pretty much a different way of writing if else statements, and you can chain them vertically as well. The only difference is that they return the value to which each expression evaluates to, so yeah. You can even go as far as having multiline code blocks, as if it were an if else notation, only that it returns a vlue. But at that point, you might as well start to prefer having if else actually evaluate to expressions in the language for consistency and ease of use.
@user-bw6lh5xk2x11 ай бұрын
ternary are good if you have "condition ? a : b", maybe even "condition_A ? condition_B ? a: b : c" once you go beyond that it's just too clustered
@simonwillover417511 ай бұрын
Why not do: " if(condition_A) return a if(condition_B) return b return c "? And in your example, it should be: "condition_A ? condition_B ? b: a : c" , which is why ternaries are inferior.
@SimonBuchanNz11 ай бұрын
It's condition_A ? A : condition_B ? b : c. Always invert conditions to put nested conditions in the else, if you can't don't use ternaries!
@user-bw6lh5xk2x11 ай бұрын
@@simonwillover4175 the order here was just an example. I still prefer to use ternaries in this case. It's a personal preference
@user-bw6lh5xk2x11 ай бұрын
@@SimonBuchanNzthe order is besides the point of my comment
@SimonBuchanNz11 ай бұрын
@@user-bw6lh5xk2x the order is extremely relevant to how understandable a ternary is. It's essentially always wrong to put a ternary in the middle of another ternary.
@alexbenfaremo549311 ай бұрын
You can use the ternary inside a function. It used to "replace" simple if else, not how we put a value in a variable :)
@AdroSlice11 ай бұрын
Here's how I write ternaries using fizzbuzz(n) as an example. (n % 3) ? (n % 5) ? n : "Buzz" : (n % 5) ? "Fizz" : "FizzBuzz" Notice the parentheses around the condition. Notice how conditions and cases are cleanly seperatee. Notice how obvious it is when a case is followed up by another condition. Notice how additional nesting is indented.
@alexm910411 ай бұрын
This thing is hardly readable.
@VonCarlsson11 ай бұрын
But why? It's one (1) line shorter than the equivalent code using braced if-else statements. When exactly is it ever worth trading readability and, supposing equal readability, formatability to save a single line and a handful of characters? Single return really isn't THAT important. Furthermore, if terseness truly is that valuable you could have written as [, "Fizz", "Buzz", "FizzBuzz"][(n % 5 === 0)
@AdroSlice11 ай бұрын
@@VonCarlsson Don't worry, I'm not suggesting anyone write code like this. While I think that Primes dogmatic "never nest ternaries" is going a bit too far, I will agree that, generally speaking, better solutions exist. The only thing my comment was meant to address was how nonsensical "prettier"s uglier ternary is. The formatting they show only *arguably* makes sense for tail-nesting ternaries, but fails as a general stylistic solution.
@khangle687211 ай бұрын
Btw, PHP had an operator to compare 2 value: the "spaceship" operator , which will return 1, 0, or -1 if a value was greater, equal, or lesser than the other 25 25 // return 0 25 20 // return 1 20 25 // return -1
@felixjohnson387411 ай бұрын
Maybe I'm wrong, but I feel like that would actually be something extremely desirable. (At least in compiled languages) It means you could use a single instruction to compare then check the condition flags all at once as opposed to comparing, checking zero flag, doing something, comparing again, checking sign flag, doing something, etc. Its honestly weird how much compiler-nice syntax is completely absent from languages. I mean your CPU literally has a builtin automatic overflow detection flag, yet I've NEVER seen a language use it. The only way I've ever seen anyone check for overflows is by manually comparing the values with conditionals. WHY?! Its right there, hardware accelerated and all, why the *_hell_* are you forcing people to write all those extra lines, which turns into all those extra instructions, which turns into all those extra wasted CPU cycles?! At best stuff like this will be recognized by the compiler and optimized out, but thats a pretty big risk in comparison to just having dedicated syntax for it.
@SimonBuchanNz11 ай бұрын
@@felixjohnson3874first, your CPU might not have condition flags! x86 and ARM do, but RISC-V doesn't, and many CPUs around when most of these languages were made were far weirder. (If anything, since C got popular, CPUs have massively changed to look more like C rather than the other way around) Secondly, C++ did, in fact, add the "spaceship operator" pretty much directly, and Rust's compare operators are built on Ord::cmp, which returns effectively the same thing. So, basically, they are!
@GypsyBackwards11 ай бұрын
I never even thought about nesting ternaries. I could have lived without this information. imo they look good as one liners as opposed to if statements when just setting a variable, but anything beyond a simple single condition demands something easier to read.
@arnabbiswasalsodeep11 ай бұрын
So, here in the hardware land of SystemVerilog and even some driver coding, ternaries are preferred because if else ends up using a cpu comparator & then compares the value for true & false with branching whereas ternary makes it as a mux where input is selector which is optimised so well as binary logic circuit synthesis than if-else branches. Another thing always helps is use brackets, like be it maths or ternaries or anywhere else where needed, use brackets and any decent code text editor should highlight the encased.
@datboi_gee11 ай бұрын
I think your intuition about that inverted logic yielding a different result was spot on. The first case results in the animal being a wolf only if it is BOTH scary and can bark. The latter case disregards "canBark" entirely if isScary returns true. If I'm reading this correctly, that is. I haven't ever touched this language.
@Gregorius42111 ай бұрын
IMO they made the assumption/precondition that there aren't scary cats or bunnies, therefore isScary() -> implies canBark() another precond. is canMeow() -> !canBark() As such the cases of the truth table that changed due to the reordering were invalid.
@eej1.0711 ай бұрын
As a youtube watcher who only recently started watching Prime's streams, I got bamboozled when I learned he can have a week's worth of content coming from only one stream
@dasten12311 ай бұрын
Yeah but the price to pay is you have to endure more interactions with the idiot-chat
@MessioticRambles11 ай бұрын
And ungodly amounts of “welcome to Costco, I love you”. I literally cannot watch his streams just because of that.
@haniffaris891711 ай бұрын
@@MessioticRamblesWelcome to Costco, I love you. I'll follow you around KZbin and haunt you with that quote (jk i got stuff to do).
@blenderpanzi11 ай бұрын
iife -> when you write plain browser JavaScript and want to isolate your script's namespace from the global namespace. And Maybe also when you want to initialize a global const with some non-trivial code. Yeah, you could just use a named function for the latter, but it makes it clear that this isn't a function that is meant to be used more than once.
@CottidaeSEA11 ай бұрын
I love ternaries, but I rarely use them for this very reason. The times when I have so simple logic and values that I can just slap together a ternary like a = b ? c : d are quite rare. When I can do that I think it is amazing though. Example of when it might happen (JS example for all of you non-believers): const apiUrl = process.env.ENVIRONMENT === 'production' ? PRODUCTION_URL : STAGING_URL
@macaroni_italic11 ай бұрын
Yeah they are great to have in those niche cases. It seems like some people just think "if-else" statements look old-fashioned and gross, so they're trying to hammer ternaries into the wrong-shaped hole so their personal aesthetics don't get scuffed. A well-used ternary (e.g. to simplify a return statement) is beautiful. But if I see them all over the place in a person's code, it's a major smell. If I have to second-guess even slightly what's going on in the logic of a ternary, it needs to be done some other way.
@CottidaeSEA11 ай бұрын
@@macaroni_italic I think one of the main reasons is the crazy obsession with immutable data in the JavaScript world, so they don't want to use the keyword let. Because you could just initialize the value with the final else-case value and then the logic can be simplified to not even need else. It's not as performant as if-else, but if you're doing stuff like what is shown with the ternaries you probably don't give a damn about performance regardless.
@Endelin11 ай бұрын
Another advantage of 80 column/4 space indenting vertical code is that it's easier to read git diffs.
@theodorealenas317111 ай бұрын
This. And I almost always split the screen vertically, to have compilation errors on one side or a preview of what I'm making.
@ComposTiger11 ай бұрын
I come from the 42 school, the code style stated : Nested ternaries are forbidden. Never wrote a nested ternary since I started my career in 2017, whatever the language. Go is smart, Go does not have ternaries, be smart, use Go.
@canowyrms11 ай бұрын
I like 4 space indent but I'm more adamant about using TABS instead of spaces. I like tabs because you can just set your preferred tab-width in your editor. 2-space and 4-space can work in the same codebase with their preferred indentation without fighting.
@josefpharma471410 ай бұрын
Are you working in a team using tabs? (I never came across one doing so myself) BTW: Simply take the pattern the team is using. It takes minimal time getting used to that and is IMHO not worth any fighting. BTW2: If you edit an existing code file. The 1st thing you do is checking how did the previous authors structure and do the stuff. So that you can try to stick to existing patterns. (given that there is a pattern 🙂🙂)
@canowyrms10 ай бұрын
@@josefpharma4714 not working with any team atm but I'll always advocate for tabs. To your last two points, it assumes the authors are using anything other than their mood of the day to guide their formatting decisions. I have been on some teams where no formatting tools were used, at all, and code style was a hot mess, completely inconsistent. Obviously if sane conventions are in place, continue using them.
@argh5233 ай бұрын
To make variable-width tabs actually work, editors would need to insert spaces for everything that isn't purely indentation. Otherwise, you simply cannot do any manual formatting. This is why even in most codebases that use tabs, you still need to use a specific width, or the formatting will be messed up. So the "correct" answer for the tabs vs spaces debate is "both"
@PlGGS11 ай бұрын
"If only there was a pattern like toString()" hahaha
@JonathanRose2411 ай бұрын
Hot take: using nested ternaries in jsx is lazy. Instead of using nested ternaries, make it a component with early returns
@SimonBuchanNz11 ай бұрын
Early returns in components are a big foot gun with hooks, but linting can fix that. The bigger issue is that the point of components and JSX in general is to be declarative, so mixing procedural logic in there is somewhat confusing.
@JonathanRose2411 ай бұрын
@@SimonBuchanNz I’d argue that your hooks should be built with this in mind and be more thought out, but I suppose that could be a footgun if not well thought out
@SimonBuchanNz11 ай бұрын
@@JonathanRose24 that's... a confusing response? Any control flow that changes what hooks are called or their order is illegal, so early returns which are just begging to return before a hook is a risk regardless of if "your hooks [are] built with this in mind"? I probably just don't get what you mean though.
@acidhauss701811 ай бұрын
I remember the days before GitHub copilot and prettier where it was impossible to pick those things apart
@TruthAndLoyalty11 ай бұрын
@@SimonBuchanNz That's why hooks are supposed to be at the top. You won't early return away your hooks unless you're breaking the "rules of hooks".
@duke60511 ай бұрын
The problem with 4 space indenting is, while it makes sense for people that take pride in their work and signals "hmmmm perhaps I should break this into a function or try to find a way to prevent so many indents." Many don't care and will gladly go to 6 indents. And because I don't believe in nit picking in code reviews, the wavy ugly disgusting code stays. So that's why I prefer 2 spaces, because it alleviates people that don't care from destroying your codebase
@TruthAndLoyalty11 ай бұрын
Where do you draw the line at nitpicking? If you're seeing that regularly it's because the standards aren't good enough.
@TheBswan11 ай бұрын
Use automated formatters. Professional software engineers should never have to think about manually formatting code or arguing over preferences. My team used to argue about sorting imports, so I wrote an ESLint plugin to automate. Don't waste energy on these things
@Yupppi11 ай бұрын
I dig single depth ternary operators, feels better than if and else with their respective brackets for a single 1/0 check. Once you start chaining them, it immediately becomes a pain to reason about, somehow the syntax just becomes messy. But for single use they're kinda neat. The first example was a nightmare to read. But honestly I wouldn't like reading it in if - if else - else format either, just can't win with such short evaluation branches. But like Prime pointed out, the issue probably isn't the formatting of those statements rather than the structuring of the code at that point. The trap of solving the wrong problem.
@blenderpanzi11 ай бұрын
I've seen a KZbin short explaining JavaScript that used a terneary at statement level. When I expressed my bewilderment about that in the comments I got multiple replies defending it. "It's less to type." W.T.F. Anyway, I do use ternearies in things like this (made up example): {isLoading ? : isError ? : } Important: only tail-nesting.
@UncleWalter111 ай бұрын
New ick unlocked: nested ternaries
@weroro11 ай бұрын
Why not put a question mark on the new line? const animalName = pet.canSqueak() ? 'mouse' : pet.canBark() ? pet.isScary() ? 'wolf' : 'dog' : pet.canMeow() ? 'cat' : 'Bunny'; For me, it's super readable.
@tamasbarasz438211 ай бұрын
a scary non-barking pet yields different results
@trapexit11 ай бұрын
Just collapse scope. That rule alone will lead you to compress your code in often pretty decent ways. Conditional statement too long? Turn it into a function. Conditional body too long? Turn it into a function. Loop too long? Turn it into a function. Sometimes that isn't practical because you need a continue or break but I find this single general rule works in pretty much every language and helps you refactor code into cleaner and more concise blocks.
@TheTrienco11 ай бұрын
I prefer 4 spaces myself. I also learned to hate 2 spaces with a passion at work. It seems to be mostly the people that write the worst, nested to hell spaghetti code that insist "but you can fit more on the screen with 2". Blunt and provoking hot take: "stop fixing your shitty code by throwing shitty formatting on top of it."
@rct99911 ай бұрын
Hot take: Using spaces as tabs IS throwing shittyy formatting on top of your code regardless of how many you use....
@macaroni_italic11 ай бұрын
I feel like the 2 spaces trend is basically just HTML style infesting general programming. It makes sense with HTML because you invariably nest like crazy when you're writing it (if you want it to be remotely legible anyway). But it's just not needed for actual programming. I always go with 4, always have, always will.
@TheTrienco11 ай бұрын
@@rct999oh, that is the next step. I'm a firm believer in "indent with tab, align with space". Everyone can use their own tab width and it will still look right. Unfortunately it takes more effort, many IDEs don't support it out of the box and therefore most people won't bother doing it right.
@paxdriver11 ай бұрын
The cure is switch statements. It is so much clearer to establish a list of possible conditions and dump them in a switch so people know the possible cases and their specific outcomes. 4 space tabs also helps a ton.
@0dsteel11 ай бұрын
6:41
@marcomongalo332811 ай бұрын
I learned to love ternary statements when the clauses are short and easy to follow. Though, I rather "?" at the beginning of a line, such as: ` canBark() ? IsScary() ? "wolf" : "dog" : canMeow() ? "cat" : "probably a bunny" ` It becomes hard to read ternaries with too much nesting, but then you shouldn't use ternaries in the first place. If-then is unnecessarily verbose if the clauses are short enough to follow as a ternary. ` canBark() ? isScary() ? "wolf" : "dog" : canMeow() ? "cat" : "probably a bunny" ` also works for me. Doesn't feel too crazy if you keep up to one ternary inline
@Emil_9611 ай бұрын
I like ternaries cuz they shorten my code. I'd never do nested ternaries though. They exponentially lose readability.
@TrueHolarctic11 ай бұрын
Yup, use ternary only if it checks one variable, maybe two if checking if they are true/false otherwise its a full if or a function. I dont want to follow crazy lines back and forth when debugging.
@Glinkis11 ай бұрын
Shorter code is not better. It can sometimes be, but is most of the time not.
@WralthChardiceVideo9 ай бұрын
I like this. I don't do javascript, but I often use similar constructs that try to return as soon as possible, so the logic is nicely readable.
@connorskudlarek859811 ай бұрын
I agree very much with the ternary hellscape. This feels way worse than callback hell. The moment you grab a second ternary statement is the second you should ask "is this really the best way to do this?" My immediate though would be to setup an object containing my functions and loop over them. The first true function tells me the pet, and I can always add more pets. function isDog(){if(pet.canBark()){return "is dog"} function isCat(){if(pet.canMeow()){return "is cat"} function isMouse(){if(pet.canSqueak()){return "is mouse"} const pets = {dog: isDog, cat: isCat, mouse: isMouse} Then just loop. You won't need 4 ternary operators to get to "is probably bunny".
@VenomousCamel11 ай бұрын
My theory with indentation resets based on context. Like 2 indents deep is great, until your first column is consumed by a class/namespace item -- now function names are the first indent, and their base-level code is the second and you can't use if/for/while/switch etc
@Kotfluegel11 ай бұрын
As long as languages, don't have a syntactic better way of expressing "condition, thenValue, elseValue" where "then" and "else" are evaluated lazily, ternaries are here to stay. You can't replace them with a function call: ternary(condition: boolean, thenValue: T, elseValue: T): T because then and else are not evaluated lazily. And using something like ternary(condition: boolean, thenValue: () => T, elseValue: () => T): T is lazy, however you need to construct two lambdas. You really need maybe my first version of the ternary to be a language key word, that just looks like a function call, but the compiler provides special support not to evaluate on of the two branches.
@airkami7 ай бұрын
Yo, shout out to v4nderstruck in twitch chat who said, “why is it 16:9 and not 9:16” If you have never used a vertical monitor to view code, I definitely recommend trying it sometime. However, the actual answer to the question is because our vision is already wider than it is tall. If you want to try writing and reading code as top to bottom right to left and 9:16 you totally could try it and maybe it works better depending on which part of the world someone is from and how their native language is written. I think however, that code is less like literature and more like math. So if you want add 60 different numbers together the easy way, you put 4 columns of 15 lines Get 4 subtotals, then 1 column and 4 lines and There you go, despite the human eye and monitor system matching, the math and coding match each other rather than the human eye. This could also be by design as numbers are abstract
@robertlenders875511 ай бұрын
The thing you actually want is if-expressions. Ternaries are preferred to if statements because they have a return value so you have control flow like early-return scoped to just the expression. If statements force you to declare some uninitialised variable upstream to hold the result which is a potential source of bugs. Definitely agree with not putting logic in a ternary or if statement that would be better served as a property of the class like a tag name.
@jomohogames11 ай бұрын
I realized how truly blessed and innocent my existence is, to have neither experienced nor conceived of nested ternaries until this day. What a corruption of the law. A ternary is a shorthand a simple one liner, never to be used upon itself, but merely to express the obvious with elegance. Never will I forget this dreadful sight of nested terneries. And never shall I break this law myself.
11 ай бұрын
The problem with nested ternaries - you have to parse the *whole* thing in your head to understand it, and to modify it in a single place. It is difficult to jump in the middle and just add / modify / remove a clause.
@grumpylibrarian11 ай бұрын
You have it completely backwards, especially if you like restraints. The benefit of the ternary is that it has exactly one way it can operate. Everything goes into a dichotomous structure. A ? B : C shows you instantly that it's going to be B or C, not both or neither. If you see this: A ? B : C ? D : E You know immediately that if it's B, it can't be D or E. The flow will always stop there and proceed no further. Amongst other things, if you have expensive checks you can usually factor the list to put those checks toward the end, so they'll never run unless all the easy checks have already failed. Meanwhile, there's nothing more evil than an "else" statement in programming. "else," "else-if," and statements snuck between checks all have entirely different outcomes, and it's much harder to follow along mentally. "else" also invites nested ifs, which seems to be the root of your real concern in this video: nested checks are just very mentally taxing on the person reading the code and will be more likely to contain errors and be more difficult to refactor. I use if statements---not if-else but only if statements---for when I need A) actions instead of values and B) non-mutually-exclusive results. B, D, and E are obvious and necessarily excluded results in my example above; a few if statements are not. Another really, really, really bad pattern I see far too often with if statements is the delayed variable assignment, such as this: let myvalue if(condition1){ myvalue=1 }else if(condition2){ myvalue=2 } It's easy to lose precisely when and why mayvalue gets set. It's also possible to never set a value for myvalue. It requires a mutable instead of a constant value. Compare to const myvalue=condition1 ? 1 : condition2 ? 2: 0 Now we're forced to put a fallthrough value, and if both conditions fail, myvalue now equals 0 instead of undefined or null. We see instantly where myvalue is set. myvalue is now immutable. The syntax might look ugly to the uninitiated, but it's common to all C-style languages. You've had almost 50 years to get used to it. No excuses. And I'm sorry you've never had a project where you had to take a heuristic approach to define a value. Maybe you don't like seeing all of the logic in a concise format with zero possibility of ambiguous or unassigned fallthrough values, but this logic is happening somewhere in your program. Its worthwhile to minimize the checks you need and certainly keep it at one level if at all possible. I have a rule that if a check can't fit onto a single line (I also use 80 columns as a hard rule), then I have to store the check into a well-named variable to use within the actual ternary / if construct. But if I have to have 20 (vertical!) rows within the ternary statement, that's not a problem at all. That's conciseness.
@colinmaharaj11 ай бұрын
2:00 I don't mind having a bunch of nested if else statements, I do a database write in one of my apps,... if the feature is turned on, if the is connection is active, if the condition in the data is met, If there are no other write operations taking place on the DB, if there is a minimum amount of records in the queue to write, if there is minimal activity in other threads, then I write.
@colinmaharaj11 ай бұрын
If I only have one record in my queue, and 4 seconds has passed, I will write it. If I have records coming in the queue, and a record comes in once per second, if the queue reaches 32 records, I will write unconditionally. (I'm just demonstrating that I have more ifs to deal with than I said before)
@tylermfdurden11 ай бұрын
I actually just came up with a revolutionary way to re-write this! Start with: const animalName = pet.canSqueak() ? 'mouse' : pet.canBark() ? pet.isScary() ? 'wolf' : 'dog' : pet.canMeow() : 'cat' : pet.canSqueak() ? 'mouse again' : 'bunny'; and transform it into: const animalName = pet.name; which I think we can all agree is easier to read and understand, not to mention easier to maintain.
@St.JohnWort11 ай бұрын
People forget that function calls take some overhead, and if you have even a few inside a nested loop, it can start to take a toll on your runtime. Having a ternary operator cleans the code up from 5+ lines to a single line while not reducing the readability of the program in anyway. If anything, a ternary makes it even easier to read since all of your if statements are in a single line of code neatly formatted. If you can't recognize a single ternary operator and what it does then you obviously shouldn't be a programmer, let alone a software engineer. However, I do agree that nested ternaries add too much complexity into the branching and can quickly become overwhelming. But functions are not the answer, given the increased overhead with each function call. It is far better to just make it a bunch of if, if-else statements or to use switch cases. Switch cases have the added benefit of using jump tables which are significantly faster than if statements and functions.
@Innengelaender11 ай бұрын
I just like the simplicity of a (early) return and it being clearly visually different from opening another (potentially nested) branch with if (forget about else alltogether). If you can bring that to an inline-expression - maybe something like a match-expression, that would be amazing.
@Lammot11 ай бұрын
What is wrong with prefixing a line with an symbol and indenting internal ternary? string result = pet.CanSqueak() ? "mouse" : pet.CanBark() ? pet.IsScary() ? "wolf" : "dog" : pet.CanMeow() ? "cat" : pet.CanSqueak() // why is it here? we are on a branch where this returned false already. ? "mouse" : "probably a bunny" Ironic that their more readable version prevented them from finding and unnecessary check. But regardless, I doubt any amount of styling can fix this tree being unnecessary in the first place.
@aidanbrumsickle11 ай бұрын
I think one thing that pushes people towards ternaries in languages like JS is when each branch is a different initial value for a variable that can otherwise be const. When you have a simple condition, `const x = cond ? a : b;` feels much cleaner than `let x; if (cond) { x = a; } else { x = b; }`. Fundamentally though, this is a flaw of languages that have both constness and the distinction between expressions and statements. In these languages, extracting a function / method is the only way to do multiple things in one expression, barring cursed approaches like abusing the comma operator.
@seflue11 ай бұрын
The fact, that the flaws in the logic of the examples are easily spottable speaks for the quality of the formatting rules. I actually like compact expression based statements without a lot of noise. Using question marks and colons as shorthands for "then" and "else" helps me to fokus on the relevant things. That this kinds of nested logic are a smell for other problems in the program structure in many cases is a different debate. Depending on the domain it is sometimes hard to avoid. If the domain dictates such complex rules, you need to write them down somehow. You should avoid unnecessary complexity but the necessary complexity should be as easy to read as possible. And if the style actually helps you to spot and simplify unnecessary complexity in a simple and comfortable way, thats a plus for me.
@kapobajza370811 ай бұрын
I don't know why people think that you can only use ternary operators inside of React's JSX components. I mean instead of doing this: return someCondition ? : someOtherCondition ? : You can simply do this: let MyComponent = null; // [1] Or: let MyComponent = ; if (someCondition) { MyComponent = ; } else if (someOtherCondition) { MyComponent = ; } else { // If you went with the other option [1], you can get rid of this else statement MyComponent = ; } return MyComponent;
@Luxalpa11 ай бұрын
The problem with your argumentation is this: IIFE and nested ternaries exist in other languages and are the recommended way to write code there, they just have a different name. In Rust, IIFE's become block expressions and ternaries become match- and if-expressions. They are the exact same pattern and follow the exact same use cases. So why is it bad when people use it in JS but good when they do it in Rust or Python? Whatever problems are being solved by block- and if-expressions in Rust, those same problems also exist in JavaScript and syntactically they are very similar. So why would you use a completely different solution? You could also just wrap everything in functions in Rust and never use any of these features with the same argumentation.
@calder-ty11 ай бұрын
Prime was starting to sound like Uncle Bob there for a second. :ducks:
@ccs432111 ай бұрын
I do think lot of nested if- else can be fixed with switch
@MarkoZastavniković11 ай бұрын
Regarding the second example, no it is not the same because in first example you had nested "if" but in second example nothing is nested, instead everything is chained up with "else if". From my point of view first example is the best because you can see the "if" and "else" parts pretty easy but also understand what is nested based on padding. Even Prime read that first example pretty quickly and correctly but got confused on other ones.
@ryangrogan683911 ай бұрын
0:20 Oh god, i didnt even realize you could do something so heinous with the ternary. I have never attempted such black magic in my life.
@joe5head11 ай бұрын
there is also an eslint rule for cyclomatic complexity that helps to give a unified 'code smell'
@apollolux11 ай бұрын
If I nest ternary statements more than one deep in my own code, I try to go left-to-right in the logic and even if it loses a small bit of overall performance precalculate as many values as necessary before the checks whether I use those precalculated values again after the check or not. More often than not, I'd rather avoid the use of ternary syntax if I find myself needing an overabundance of parentheses to group the returned values. Related, I once looked at someone else's C++ (a particular video game console emulator, IIRC) and saw that it used ternary syntax to replace traditional braced if-else syntax and flat out run full expressions rather than simply conditionally return values. I was stunned when I saw that code since I never thought about it that way before then, but after reading it a few more times to confirm its operation and reading the language spec on ternary syntax it made a lot of sense that it could indeed be correctly used that way.
@beskamir597711 ай бұрын
I agree with you. I'd never be insane enough to use nested ternaries over nested if/else statements and even then I'd still prefer another solution. Only case where I use ternaries is when it's just a simple one line if/else statement.
@AaronAlexander117611 ай бұрын
This is such a good example of unreadable code. Also, can we take a moment to appreciate the fact that this blog post is on a website for a tool called Prettier. Prettier. Let that sink in.
@almicc6 ай бұрын
Only thing that sucks is typescript doesn't let you use switch types, you are forced to use `extends ? X : Y`. If you have three possibilities then that's a whole new ternary. Unless I'm missing something, the only way to map a series of types to a series of another type is to have a huge string of ternary statements.
@sczoot628511 ай бұрын
Here’s a solution for ternaries. Have a formatting system that interprets ternaries and outputs the broken out if else if chain to ease development speed but output a consistent tried and true style
@josephdvorak924111 ай бұрын
I usually limit myself to one ternary expression per statement. If I need a second question mark, it's an indication that I can convey the concept I'm trying to express more clearly
@Gregorius42111 ай бұрын
10:17 Indeed the results are different. Killer bunny just went from "probably a bunny" to "wolf".
@w01dnick11 ай бұрын
10:45 yes, they are different. If pet canMeow & isScary & !canBark first will say 'cat', second will say 'wolf'.
@HenriqueErzinger4 ай бұрын
It's wild that the developer quoted in the article said "in a few hours I had used It a few times...". If I used a nested ternary in a year of coding I few awful and sloppy, and I'm pretty sure I've never had more than 2 condition in 23 years of professional work.
@lethicanthus11 ай бұрын
I like to write my ternaries like var = condition ? trueValue : falseValue ; I almost never nest them because, like you said, there's probably a better way, but you could easily nest that same structure in itself and not have it get ugly. I'd also recommend adding parens/whitespace, though. For those who don't know why they're a thing in the first place, unlike if/else or switch/match statements, ternaries don't cause branching in your code so they're more efficient for the CPU. They are really great for hot-paths... At least in C/C++ anyway. I'm not sure about JavaScript/Python/etc. But, I'd bet it's true for Java and C#.
@MrAbrazildo11 ай бұрын
0:10, ooh, this is awkward! The right way is to have a variable in a class, and just ask for it, not loosing performance nor getting complicated, trying to guess what it is. It's even better if, instead of a variable, this constant is given as a template argument, by a f(). 3:49, this is a long discussion, but I think quite the opposite. Horizontal code means 1 will spend less time traveling throughout the code vertically, which spends more energy, and looses a bit of focus. Plus, eyes are widescreen, they were made to see things horizontally. And also reading code is an eye thing, not a hands 1. I use tab = 2, to put more things on the same line.
@mage369011 ай бұрын
The only reason I've ever used ternaries is because I'm assigning to a variable and C doesn't consider an if-else statement to be an r-value. Also, 2 levels of nesting before you hit the 80 column mark? I recently went "while this, for i, switch that, for j, switch that, for k, switch that, for l", and didn't break column 80 once. It's horribly unreadable and I need to find a different approach (can't think of a better way to do it because I'm a noob), but it follows the rule.
@toxicitysocks11 ай бұрын
The nastiest ternaries I’ve written are part of a complex spinnaker pipeline. Spinnaker doesn’t let you write code blocks, just inline expressions evaluating to a value.
@MarquisKurt11 ай бұрын
Looks like I ought to get more Phil's Coffee, I'm still taking my switch/case with pattern matching (or just... putting it in a function!)
@RandomGeometryDashStuff11 ай бұрын
00:11 putting parentheses around outputs (`a?b:c` → `a?(b):(c)`) will make this readable
@JohnHMercer11 ай бұрын
I rather write ternaries with the question mark below the condition: const animalName = pet.canSqueak() ? 'mouse' : pet.canBark() ? pet.isScary() ? 'wolf' : 'dog' : pet.canMeow() ? 'cat' : pet.canSqueak() ? 'mouse' : 'probably a bunny'; // 4 lines indentation So it goes like: Condition ? true // 2 lines indentation : false // 2 lines indentation If you follow the ? up, you get to the condition of that question mark("if true" statement). And if you follow the : up, you'll get to to the "if true" statement of that ternary branch(?).
@krtirtho11 ай бұрын
I use ternary operator so much, I'm afraid sometimes those long nested ternary operations might result in an AGI (Artificial General Intelligence)
@NuncNuncNuncNunc11 ай бұрын
Ternaries have perfectly good use case - assignment of const between exactly two alternatives taking up either one line or three lines, all alternatives on one line or each on separate line. Why isn't Copilot rewriting you nested ternaries to more readable code that actually catches all the edge cases you are trying to account for?
@emptystuff159311 ай бұрын
I only ever use the simplest ternaries, else it becomes unreadable. The condition may contain a comparison or a function call, or may be a variable. The results may be a literal or a variable. Nothing more complex than that.
@thekwoka470711 ай бұрын
If else (especially if you need to use let, and not like a return) can easily get real ugly for simple cases. It's obviously nicer when the branches have logic in them, but when it's mostly a simple mapping of some conditional state to some value it's just a lot more going on.
@pesterenan11 ай бұрын
If you need a nested ternary, I think it's better to ask for more time to implement the task that you're working on.
@g.c95511 ай бұрын
the new proposal is actually how I used to format ternary until I started using prettier and just accepted whatever it decided. 😂
@boman98711 ай бұрын
What if we had a way to “see” it in multiple ways? People with different minds could process it the best for them. But functionality remains. (Something like one of those Bibles with side by side translations throughout.)
@namewastaken36011 ай бұрын
With returns you may as well use ifs. Assignments at declaration are where ternaries make sense.
@namewastaken36011 ай бұрын
And if I ever found myself nesting ternaries, I'd add brackets just for readability.
@clakams11 ай бұрын
Isn’t long code vertical code? Truncated by 80 is good to prevent wide code, no?
@simonwillover417511 ай бұрын
So do you prefer if-else then? I just like ternaries BECAUSE they look more abstract then if-else. And because I like the idea of "outputting the yielded result after selecting the correct tree. I guess there is a really nice way to do this functionally (I often feel the urge to convert nested ternaries into nested functions), but I like "in-line" feeling the ternaries give off.
@AlexandraDeas11 ай бұрын
The solution to this is having conditional blocks return values. Ternaries provide this with a weird syntax that's difficult to read
@Unordinal11 ай бұрын
If you're going to nest to the (frankly insane, IMO) degree shown in the video and you like the feeling of the one-line, just use a function. You can even do an inline function in a lot of languages, just do something like `const animalName = () => { ... if else returns in here ... }`. It's just much easier to follow and refactor if necessary.
@CRBarchager11 ай бұрын
I only use ternaries instead of single if-else statements. I find it confusing to look at when I add more than one set of ? : and have to think about the code.
@Rudxain9 ай бұрын
I wish there was a lang that had these: ``` (cond) ? (truthy) : (falsy) ``` It's like Rust (parentheses are mandatory, for explicitness), and JS (terse expression syntax). The best of both worlds. Conditional-branching is so common that we don't need english keywords, that's why I advocate for language-neutral symbols. Y'all gotta be grateful that Java doesn't use `{if (cond) then {truthy} otherwise {falsy}}`
@rusmaakatupal472311 ай бұрын
The best is to write branchless code. Imagine you want to return the smallest number between 2 numbers. Instead of doing something like this : value = a > b ? b : a; or even worse something like this : if(a > b) value = b else value = a Do this : value = ( (a > b) * b) + ( (b >= a) * a); This specific exemple might not optimize your code. But it's a simple way of demonstrating the concept. (a > b) will return one or zero (b >= a) will return one or zero Cheers
@spyroninja11 ай бұрын
That's not simple at all
@HalfMonty1111 ай бұрын
My main use of ternary statements is to collapse optionally undefined variables or function responses into a either the definite Type response or default case of a definite type because I hate this?.stupid?.garbage and I want my downstream logic to only have to consider the case of definite types and not optional nulls or undefined's where possible. I have maybe only once in my life used nested ternaries and it made sense at the time.