We Need To Talk About Ternaries

Sdílet
Vložit
  • čas přidán 24. 07. 2024
  • It's no secret that I'm not a huge fan of ternaries. Sadly, they're a necessary evil.
    Prettier ternaries article: prettier.io/blog/2023/11/13/c...
    Check out my Twitch, Twitter, Discord more at t3.gg
    S/O Ph4sOn3 for the awesome edit 🙏
  • Věda a technologie

Komentáře • 382

  • @realist.network
    @realist.network Před 6 měsíci +154

    The code is cleaner when splitting it out into components, agreed; however, I don’t think it should be the job of a component to decide whether itself should be rendered or not (e.g. the Sidebar component returning null if the sidebar is not supposed to be open).
    I think the caller/consumer of a component should decide whether it’s to be rendered or not, and components themselves should be just that: The component markup and any features/state _within_ the component.

    • @tehtriangle6660
      @tehtriangle6660 Před 6 měsíci +22

      100%. By adding in the conditional, you're now making the component consider state outside of it's immediate concern.

    • @permanar_
      @permanar_ Před 6 měsíci +3

      Idk why but kinda agree with this.

    • @Benedictator123
      @Benedictator123 Před 6 měsíci +4

      Can we have this discussed cos this feels important

    • @TheNeonRaven
      @TheNeonRaven Před 6 měsíci +8

      100% agree if you're talking about actual independent components, however this makes more sense if you're just breaking out small parts within a single file, and those "sub components" aren't externally accessible. This is pretty much refactoring out a function and failing early to make it more concise.

    • @fullstackjedi
      @fullstackjedi Před 6 měsíci

      While I agree this is just contrived example.

  • @jwr6796
    @jwr6796 Před 6 měsíci +38

    I use ternaries a lot in Svelte property bindings. When it's a simple case, it's way easier than creating a whole function for it.

  • @alastairtheduke
    @alastairtheduke Před 6 měsíci +95

    The problem with breaking it out into components is that it's verbose. Most people using && use it for small pieces of content, not anything huge that makes sense to break out into its own component.

    • @oscarhagman8247
      @oscarhagman8247 Před 6 měsíci +10

      well yes we mostly use && for small little things, but as he said when you start to fill up your markup with too much ternary (especially nested ones at that) then it's a good idea to break it out into a component to keep it clean. He didn't say don't use them at all, just don't overdo it

    • @cooltrashgamer
      @cooltrashgamer Před 6 měsíci +3

      Another solution with the control flow discrepancy, you can treat it more like a ternary guard clause:

      {!arr.length ? null
      : arr.map(el => {return (el % 2 === 0) ? null
      : {el}})}
      Makes it a little cleaner when your null case isn't so far away from the ?

    • @Svish_
      @Svish_ Před 6 měsíci +1

      And now you have to go find those components, to figure out what happens if the state changes. For small stuff, I rather use `&&` and `? :` every time.

    • @mharley3791
      @mharley3791 Před 6 měsíci +6

      I think verbose and easily readable is better than terse and hard to follow

    • @JamesW6179
      @JamesW6179 Před 6 měsíci +10

      I have slowly come to link "verbose" as a synonym for "maintainable".

  • @semyaza555
    @semyaza555 Před 6 měsíci +181

    It’s crazy that it’s about to be 2024 and devs aren’t just returning null for React components.

    • @nicosoftnt
      @nicosoftnt Před 6 měsíci

      It was 2024 for me when you commented this

    • @nathangwyn6098
      @nathangwyn6098 Před 6 měsíci +2

      Explain? Is this a jab at react?

    • @semyaza555
      @semyaza555 Před 6 měsíci +5

      @@nathangwyn6098 it’s a jab at React devs.

    • @semyaza555
      @semyaza555 Před 6 měsíci +1

      @@nicosoftnt what time zone?

    • @nathangwyn6098
      @nathangwyn6098 Před 6 měsíci +1

      @semyaza555 I don't get it though lol ita going over my head. If you just return null with all your components nothing will be rendered? X.x

  • @A.Dalton
    @A.Dalton Před 6 měsíci +5

    I hope you discuss more technical topics like this.

  • @Exilum
    @Exilum Před 6 měsíci +37

    8:40 T[0] is still different from T[number]. I know you know, but some viewers could be misled.
    for example for a type like this: [number, string]. Typescript knows your first element is a number, your second is a string, and it has two elements. So T[0] will be number while T[number] will be number | string.

    • @mart3323
      @mart3323 Před 6 měsíci +6

      Was about to point out the same, but while double checking in ts playground i noticed the example wasn't recursive either.
      To unwrap arbitrarily nested arrays, it would have to be Flatten in the true branch

    • @andreasherd913
      @andreasherd913 Před 6 měsíci +1

      well this is done with T extends (infer R)[] ? R : T, not T[0]

    • @Exilum
      @Exilum Před 6 měsíci

      @@andreasherd913 T[number] as in the example works just fine, I see no need to infer a second temporary type, it's just extra processing for your IDE.

    • @happylittlesynth
      @happylittlesynth Před 6 měsíci +1

      Can someone please explain this a little further? I've re-watched this part multiple times and I still don't quite understand why you need to do this (also a typescript n00b)

    • @Exilum
      @Exilum Před 6 měsíci +2

      @@happylittlesynth Imagine types as being a special kind of value.
      We don't know anything about T at first.
      When you do T extends any[], you are checking if T is included in the definition of any[], meaning, T must be an array.
      We still don't know what T contains. It could contain a type, several types, etc.
      T[0] tells typescript to take the first element of T. If T is an array of numbers number[], it'll be number. If T is an array of strings string[], it'll be string.
      If T is an array contains both strings and numbers (string | number)[], it'd be string | number.
      But if string has a precise type, for example [number, string], we know three things:
      1) it has exactly two values
      2) the first value is always number
      3) the second value is always string.
      As such, T[0] would be number.
      0 can be thought of as the type of any number whose value is 0. Because the definition is so precise, it's just 0.
      When saying T[number], we are asking typescript what the result would be of indexing over the type of any valid number.
      It's a wider definition, a different type, but the same operation.
      The valid numbers here are 0 or 1, so the result is either number or string, number | string.
      Thus, in our example:
      T[0] is number
      T[number] is number | string
      If you wanted to use the type of the values inside T later on, using T[0] could create a bug if T contains more than a single type.
      When you're making a generic like this, you don't know how it could be used in the future, so you want to cover your bases. What if you forgot days later that your generic flattening type just doesn't work with more than one type per array? So while generics should be as tight as possible for clarity, you should also avoid losing information along the way.

  • @t0ssebro
    @t0ssebro Před 6 měsíci +3

    I tend to overuse ternaries because I wasnt sure if creating a bunch of components with properties that drills was good practice. Thank you for sharing your opinion! I will try to change my practice and see if I find a preferred one

  • @SamuliHirvonen
    @SamuliHirvonen Před 6 měsíci +8

    In the first example you can just map over the array without any checks: mapping over an empty array renders nothing. No checks on contacts.length are necessary.

    • @mintlata
      @mintlata Před 6 měsíci +2

      Sometimes you would want to show something to the user that the array is empty, like a message ("You don't have any..."/"This list is empty") or an icon or something, that's where ternaries (or just a simple if-else) is good for.

    • @ea_naseer
      @ea_naseer Před 6 měsíci

      ​@@mintlatacouldn't you just pass the html as a string to a variable and then after mapping check if that variable is null. If it is return your special message if not return the markup. That is verbose but much cleaner IMO

    • @SamuliHirvonen
      @SamuliHirvonen Před 6 měsíci

      @@mintlata yeah, and often you don't want to render the surrounding wrapper at all for 0 elements, then lifting the length check higher up makes more sense than in the example.

    • @DaviAreias
      @DaviAreias Před 6 měsíci

      Just put !!contacts.length

    • @mintlata
      @mintlata Před 6 měsíci

      @@ea_naseer I’m not sure I understood your idea. Can you give an example?

  • @vaggelisshmos6695
    @vaggelisshmos6695 Před 6 měsíci +1

    Happy new year Theo!!!

  • @iceinvein
    @iceinvein Před 6 měsíci +2

    I've always ended up putting a lint rule to block and nested ternary. If you need that level of complexity to figure out what you should be rendering just make a function

  • @dansurfrider
    @dansurfrider Před 6 měsíci +2

    I already was subscribed, so I don't understand why the type error, but I loved the gag! :)

  • @TimBell87
    @TimBell87 Před 6 měsíci +2

    I haven't actually made use of ternaries in js but my immediate thought was regarding your usecase:
    What if you use the ternary like it's an if guard?
    Invert the boolean check so null is specified first.

  • @Noam-Bahar
    @Noam-Bahar Před 6 měsíci +10

    Top tier subscription reminder with the literal type 😂

    • @DavidWMiller
      @DavidWMiller Před 6 měsíci

      Made me rage quit the video 🤷🏻‍♂

  • @Exilum
    @Exilum Před 6 měsíci +8

    I don't necessarily dislike the choice prettier made. But having the parenthesis at the end of the line while the colon is at the start is a net negative to me.
    I'd much prefer for both to be at the start.
    With your example, I'd prefer:
    type Something =
    T extends string
    ? T extends "a"
    ? "a"
    : "b"
    : T extends number ? "number"
    : "other"
    If you if else can't be at the same level, I'd at least like both paths to be, just like in regular programming. Questions in languages are already annoying in that you must rely on other clues to determine it is a question, as the question mark comes at the end. Taking hints from natural language isn't always great.

  • @Lampe2020
    @Lampe2020 Před 6 měsíci +2

    Well, I often use ternaries (in rare cases even nested ones) to make the code in my webpage's JS smaller and less to type. For example, I have a function that generates a lot of numbers that in the end should be packed into a string with the backtick string functionality. Instead of writing an if/else statement I just type the string template and in the optional parts I put a ternary to either place the number there or if it's a certain value put a placeholder or nothing there.

  • @veritatas678
    @veritatas678 Před 6 měsíci +13

    Happy new year.
    Creating a bunch of functions and components can also just make a file hard to organize.Personally I had to develop a system where I move functions around so similar functions are closer in the file

    • @hannad
      @hannad Před 6 měsíci +2

      Too many files. Too many components In a file. I have heard this countless times . All of this is just messy. We are convincing ourselves that this is better than that. I think the whole jsx was a mistake. But there is no better alternative aswell.

    • @ccgarciab
      @ccgarciab Před 6 měsíci

      Just Svelte, guys

  • @wagnermoreira786
    @wagnermoreira786 Před 6 měsíci +3

    So Theo you're ok with returning null from a component? I've always avoided it, and prefer to not even call the component in the case it shouldn't render. Do you have any reasons to use null?

    • @jordan59961
      @jordan59961 Před 6 měsíci

      same

    • @victorlongon
      @victorlongon Před 6 měsíci

      Keep doing that, passing a boolean to show or not the component is just dumb, imho 😊

  • @JellyMyst
    @JellyMyst Před 5 měsíci +1

    I do quite like ternary operations in my code, but I do find that a good rule of thumb is to fit them in a single line. If one spans multiple lines, consider another option. As small as possible, and no nesting. Then they become clarifications rather than obfuscations.

  • @LandonGavin
    @LandonGavin Před 6 měsíci

    Happy new year!

  • @esra_erimez
    @esra_erimez Před 6 měsíci +4

    Hello wonderful person watching this wonderful video

    • @obaid5761
      @obaid5761 Před 6 měsíci +1

      Hello wonderful person opening the replies to the comment of a wonderful person saying hello to all you wonderful people

  • @arjundureja
    @arjundureja Před 6 měsíci +3

    6:35 This pattern could lead to performance implications though. What if Sidebar needed to query some user data using a hook? Since hooks can't be called conditionally, we'd have to run the query even if the sidebar is closed. It would be better to just not render Sidebar at all by conditionally rendering the component in the parent

    • @iceinvein
      @iceinvein Před 6 měsíci

      depends on the query you can choose to run the query only if sidebar is open

    • @arjundureja
      @arjundureja Před 6 měsíci

      @@iceinvein Sure but there could be many other side effects as well. It could get messy to conditionally run all of them

    • @lord_kh4n
      @lord_kh4n Před 6 měsíci

      Mind you that this is just an example, so different solutions are still required to be researched

  • @w1atrak1ng
    @w1atrak1ng Před 6 měsíci +2

    6:57 loved that type error

  • @DaxSudo
    @DaxSudo Před 6 měsíci +1

    Interrupted New Year’s party for the anxiety of ternaries.

  • @jekuari
    @jekuari Před 6 měsíci +1

    what about using the nullish coalescing operator (??)?

  • @shaunmodipane1
    @shaunmodipane1 Před 6 měsíci

    What about the use of ternaries in tailwind classes? For me, I have no problem with it especially when the class depends on state.

  • @alexenax1109
    @alexenax1109 Před 6 měsíci

    I loved this video! Great content Theo!

  • @fregge3095
    @fregge3095 Před 6 měsíci +1

    Rule of thumb I use in the code review is that the "short branch" should go first, then you can reduce the mental cost of keeping the context of the ternary

  • @user-nx3ot8zr2l
    @user-nx3ot8zr2l Před 6 měsíci

    I sometimes use a function inside that jsx syntax so I can use if statements

  • @MARKOTHEDEV
    @MARKOTHEDEV Před 6 měsíci

    Happy new year bro😂😂😂😂

  • @StephenRayner
    @StephenRayner Před 6 měsíci

    Happy new year 🎉

  • @edsonboldrini
    @edsonboldrini Před 6 měsíci

    First video I'm watching in 2024, have a nice year guys

  • @Kitulous
    @Kitulous Před 6 měsíci

    my favorite ternary syntax looks like this:
    condition
    ? if-value
    : else-value
    then all nested ternaries get indented as well:
    condition1
    ? condition2
    ? ifvalue2
    : elsevalue2
    : elsevalue1

  • @SteinGauslaaStrindhaug
    @SteinGauslaaStrindhaug Před 6 měsíci

    I tend to find it more readable if the syntax is fairly terse (not ridiculously terse like array programming languages) and unless you're reusing a function or component; I usually prefer large functions/components over a bunch of small ones. While I've always been prone to write rather large functions; when I was younger I found myself splitting out in to sub-functions a lot more than I do now, these days I will usually only split out sub functions if it makes the code significantly shorter or of it makes scoping easier... I will often even often restructure the code so that I can use fewer functions if possible.
    End I wonder if it's not only experience/old-school preferences, but also physical aging. I need bigger fonts to see well these days (I no longer prefer dark mode during daytime either because my eyes need more light); and I've always preferred usning a single and fairly small monitor for coding (too big screen means a lot of wasted white space blasting light at me, or distractions in my peripheral vision if I use non-maximised windows); so with a larger font I have less screen space than before and code is much easier to reason about when you can see all the relevant parts at once. And while ternaries have the disadvantage of using very small symbols; at 18 pt font size they're still quite visible.
    And I really can't stand (and I never have) having the logic of some feature split over several files. I despise languages that require you to put each thing in it's own file, because those implicitly requires you to split your logic over several files if there is any code re-use at all.
    But I'm sure for the kids who write code in microscopic fonts such as 10 or even 8 pt it could be hard to see a colon since it's a just two faint antialiased blobs. And if you write in microscopic fonts, and maybe even use huge and multiple monitors, maybe having the logic split up into dozens of verbose named functions or components doesn't bother you as much as it bothers me, because you can see the whole content of maybe four 80 line files at once; while I normally can only see around 35 lines of one single file at the time.

  • @jonathangamble
    @jonathangamble Před 6 měsíci +309

    The problem is JSX not ternaries. React users pretend JSX is superior in every way, when it can't handle basic loops or conditionals without a hack.

    • @MrMatheus195
      @MrMatheus195 Před 6 měsíci +29

      But the alternatives are as ugly as jsx

    • @gilatron1241
      @gilatron1241 Před 6 měsíci +7

      Blade templates are pretty nice

    • @AdityaPimpalkar
      @AdityaPimpalkar Před 6 měsíci +12

      No one likes this. I don’t like it either, but there is still less adaption of other frameworks like svelte or solid in the industry. Vue is the only one I have seen quite a bit of decent adaptation. Blaming framework users is a cop out thing to do when you fail to see what framework the market still uses and continues to keep using. He is showing how we can use best practices to tackle this

    • @geoffreyolson9720
      @geoffreyolson9720 Před 6 měsíci +31

      Loops? Since when has array methods not been enough? It's easy to read as well.

    • @IsuruKusumal
      @IsuruKusumal Před 6 měsíci +3

      I love how compose lets you do simple if-else without hacks like this

  • @nonzz3ro
    @nonzz3ro Před 6 měsíci

    Any time I make a new component my job requires me to make a new unit test suite and Storybook story for it so I tend not to make new components if I don't absolutely have to

  • @MrSofazocker
    @MrSofazocker Před 6 měsíci +1

    4:14 whats the logic behind wrapping the arguments into props?

    • @loic.bertrand
      @loic.bertrand Před 6 měsíci

      I guess it avoids repeating parameter names (for actual parameters + for types). It also makes it clear on usage when a variable is a prop or not.

  • @mk4dea
    @mk4dea Před 6 měsíci

    One of the things I liked about templating languages like handlebars was how readable they were (of course they have their own shortcomings).
    I do agree with the arguments for encapsulating the ternary behavior for readability. However I also agree with the argument that doing so will put the responsibility on the encapsulating component for worrying about state outside of itself, and the parent should probably be the one determining whether a component should show or not.
    What about a nice middle ground such as creating a conditional component to handle this behavior?
    If we have a component that encapsulates the behavior, we can leave the inner component to worry about its own state, and the parent still gets to determine whether the child renders or not:
    //

  • @0xPanda1
    @0xPanda1 Před 6 měsíci

    Happy new year

  • @najlepszyinformatyk1661
    @najlepszyinformatyk1661 Před 6 měsíci

    4:45 but in vue and probably in svelte (i haven't tried svelte yet) you cannot just return null like in react. In those frameworks you always need to define condition in the template.

  • @conorx3
    @conorx3 Před 6 měsíci +7

    In my opinion, the example with more components was not "clearer", but for a big ternary example, I can see why it would be better.

    • @a-yon_n
      @a-yon_n Před 6 měsíci

      You don't have to use ?:, you can instead use !!

  • @Spinikar
    @Spinikar Před 6 měsíci

    🎉 Yup. This is really good practice. I use tenraries a lot but never in react jsx but even still, I'm finding more and more just preferring to use an if guard statement.

  • @RubixCubed3
    @RubixCubed3 Před 6 měsíci

    Aren’t regular if/else statements also faster than ternaries?

  • @budi6881
    @budi6881 Před 6 měsíci

    what a great way to start the new year 🤣

  • @Nocare89
    @Nocare89 Před 6 měsíci

    Separation of concerns should be the first goal for sure.

  • @adrianknapp
    @adrianknapp Před 6 měsíci

    Amazing content!

  • @coredeadman5980
    @coredeadman5980 Před 6 měsíci

    I think && is just fine if you don't overdo it. I mean if the codepiece is really complex you may outsource it into its own component, but even then i would put the condition into the outer component with &&, since it is really easy to read and understand for me that way.

  • @hardwired89
    @hardwired89 Před 6 měsíci

    thank you for clarify

  • @levsonc
    @levsonc Před 6 měsíci

    The JSX case is a great example of overengineering like with creating factories for everything in joke “senior” code. React docs itself recommend to check for condition before rendering component like {showUserInfo && }. The early returns in function is more like an anti-pattern until your are doing something like Chain of Responsibility (which is not a case here).

  • @rasmusl2067
    @rasmusl2067 Před 6 měsíci +1

    I would have thought using a debugger was on the list of things nested ternaries make harder to do

    • @GenghisD0ng
      @GenghisD0ng Před 6 měsíci

      Idk console.log seems to be working fine

    • @dputra
      @dputra Před 6 měsíci

      ​@@GenghisD0ngIMO it's better and much faster to put a breakpoint. You basically get your own steering wheel, pause and inspect each line, giving you better understanding of how a code works without reading the whole program.

  • @Leto2ndAtreides
    @Leto2ndAtreides Před 6 měsíci +1

    I feel that if you let a bunch of developers consciously format these, some better patterns would emerge for different situations.

  • @user-lz1el8ws6g
    @user-lz1el8ws6g Před 6 měsíci

    Why didn't anyone think of making a Show component like in Solid for React and an If component? But now I'm writing my UI library in which I added this, first of all, and other components that help to control my Switch type markup, and the most interesting thing is the Slot, which for some reason no one made for React

  • @AndrewErwin73
    @AndrewErwin73 Před 6 měsíci

    whoah... Theo did some OOP abstraction. What a time we live in.

  • @RicardoValero95
    @RicardoValero95 Před 6 měsíci

    You can still use ternaries and split code into multiple components

  • @Bliss467
    @Bliss467 Před 6 měsíci +1

    JavaScript absolutely needs switch expressions like c# or the when expression like kotlin.
    Kotlin also has if-else expressions instead of ternaries

    • @jfftck
      @jfftck Před 6 měsíci

      This is pattern matching, I hate the reuse of the keyword switch when the term match would make more sense.

    • @Bliss467
      @Bliss467 Před 6 měsíci

      @@jfftck match is great. I also like when. Switch never made sense to me.

  • @br3nto
    @br3nto Před 6 měsíci

    2:41 omg do people actually use && in that way??

  • @michaelessiet8830
    @michaelessiet8830 Před 6 měsíci

    Just create a component

  • @applesthehero
    @applesthehero Před 6 měsíci

    OOP brain goes "this conditional statement should be several objects, actually"

  • @jfftck
    @jfftck Před 6 měsíci

    I am of the camp that pattern matching should be in every language as it is the most readable option for returning values based on conditions - especially when multiple values are possible.

  • @user-hf7ef6nm4s
    @user-hf7ef6nm4s Před 6 měsíci

    @9:23 ternaries are an expression (meaning they evaluate to values), while ifs are just a control flow statement that don't resolve to a value on their own

  • @RafaGiemza
    @RafaGiemza Před 6 měsíci

    6:47 I love this!

  • @bananesalee7086
    @bananesalee7086 Před 6 měsíci +1

    would you say macs are making VSCode less efficient ? I only ever used windows/linux

    • @Exilum
      @Exilum Před 6 měsíci +1

      It's a good question. I don't know myself. However, I doubt any of us use vscode for efficiency.

    • @31redorange08
      @31redorange08 Před 6 měsíci +1

      Relevance?

  • @MIO9_sh
    @MIO9_sh Před 6 měsíci

    My code review notion, see more than 1 level of ternaries, your PR is rejected.

  • @Saiunai
    @Saiunai Před 6 měsíci

    “That’s not ugly, that’s readable b****” - 11:20 - Was not expecting that 😂. Great video overall

  • @smak1n
    @smak1n Před 6 měsíci

    I subscribed long time ago :D

  • @1DrowsyBoi
    @1DrowsyBoi Před 6 měsíci +1

    Every day I see the wild shit like this, going on in web-dev languages, I become far more grateful for being a C# developer.

    • @svenmify
      @svenmify Před 2 měsíci

      There’s a lot of weirdness going on in blazor too (I like it a lot, but there’s still weirdness)

  • @PieJee1
    @PieJee1 Před 6 měsíci

    I had a discussion about whether we should allow ternary. In the end I managed to convince to prevent using a ternary operator in a ternary operator.
    It's also that the operator precedence of the ternary operator over other operators differs between languages. And it's also different on right or left associative (so calling the right ternary or the left operator first). PHP even changes it after version 8!
    Still when it comes to clarity && is not clear to everyone. I started programming in C++, so I'm used to these types of hacks.

  • @moritz_p
    @moritz_p Před 6 měsíci +2

    Not about ternaries, but I think you should never do this kind of check if a value is falsy like "something.length && ..." or "if(a.length)".
    It is a tiny bit more work to write out the full condition with "!== 0" but it makes things more clear and more well defined. If youre not careful you will also end up doing weird things you didnt intend to do. For example, if you want to check that a variable str that could be null or a string is not null and you do this implicit check, an empty string would be handled the same way null would be handled. And even if you want to do that, write out two conditions because then at least people will know that both parts of the condition are intended and you didn't implicitly check for multiple conditions by accident.
    And these hacks people do with the !! are the weirdest thing. You feel so cool when you shorten your code by 4 characters but all you're really doing is making your code less readable.
    An example of implementing ternaries well is Kotlin in my opinion. The language doesn't have the classic ? and :, but instead an if statement is an expression.
    You can do something like "val x = if(...) { ... } else { ... }".
    It is more concise, allows you to handle cases where you have more than two possibilities in a readable way (else if rather than chained ternaries) and you can also write proper code into the blocks and arent just limited to returning a value.

    • @coredeadman5980
      @coredeadman5980 Před 6 měsíci

      You can also do !!something.length && ... 😂. Not that readable, but it is now a boolean and not a number anymore xD. 7:53

  • @fernandobaroni1497
    @fernandobaroni1497 Před 6 měsíci

    The company I work for loves ternaries, complex ternaries, 5-10 nested ones.

  • @kazii_the_avali
    @kazii_the_avali Před 6 měsíci

    i personally think switch statements are prittyer then if-else but i know very little about javascript as it was 5 to 10 years ago that i learned it as my first high level language and i dont fully rember how switch statements work in js.

  • @Munja12
    @Munja12 Před 6 měsíci

    6:47 good one ;)

  • @MrMudbill
    @MrMudbill Před 6 měsíci

    Sometimes I wonder why people would even need to do a `contacts.length && contacts.map`. The map would simply just not return anything if the list is empty, so it's kinda pointless to check for it.

  • @gweltazlemartret6760
    @gweltazlemartret6760 Před 6 měsíci

    6:10: you may use ternary inside your component to avoid multiple return paths.
    function Sidebar(props: ...) { return (props.sidebarOpen === false) ? null : { Sidebar : }; }
    Turn that into an arrow for even less bloat:
    Sidebar = (props: ...) => (props.sidebarOpen === false) ? null : { Sidebar : }; }
    Same for UserInfo. Ternary are not the problem. Mixing code and html definitely is.

  • @VictorMartins239
    @VictorMartins239 Před 6 měsíci

    0:40 i had this one time, it was a nightmare to figure out

  • @spicybaguette7706
    @spicybaguette7706 Před 6 měsíci

    In JSX I really like the component by SolidJS, you can very easily implement it in react:
    function Show({ when, children }) {
    if (!when) return null
    return children
    }

    • @echobucket
      @echobucket Před 6 měsíci

      It's sad in 2024 that React doesn't have the equivalent of and from solidjs built in....

  • @Fanaro
    @Fanaro Před 6 měsíci +1

    I think ternaries with "Clean Code", that is putting names on each path, is readable, but not inside JSX.

  • @rauru8570
    @rauru8570 Před 6 měsíci

    2:50 Just invert the ternary and you get your top-to-bottom reading back. That's just what you ended up doing, but inside some components.

  • @CatchMyLzzz
    @CatchMyLzzz Před 6 měsíci

    lol u should try combining the && and || and two ternary in one line (obliged)

  • @CaptRespect
    @CaptRespect Před 6 měsíci

    I really like that new formatting. Reads almost like if-elseif-else code. Although I agree that you should avoid nested Ternaries as much as possible. But the next time I run into code where a prior dev has a bunch of nested Ternaries on a single line, I'll happily reformat it to this before trying to read it.

  • @asagiai4965
    @asagiai4965 Před 6 měsíci

    I like have a rule on using ternary
    1.) Don't make it complex.
    2.) Avoid Nesting if possible.
    3.) Use component if really big (optional).
    4.) (Tip) If possible I make my ternaries readable.
    Idk if someone does the same
    (Let use the example in this video)
    {
    (sidebarOpen === false) ? //just by reading this line you know'll encounter a ternary.
    null :
    //if userInfo is false Don't render just show the sidebar Else render it with the sidebar.
    }

  • @kylemichaelsullivan
    @kylemichaelsullivan Před 6 měsíci

    Your Typescript error to subscribe to your channel is magnificent!

  • @n3x404
    @n3x404 Před 6 měsíci

    Bri thise mario style meme about it is amazing 😭😂🤣 im crying of laugh

  • @Tyheir
    @Tyheir Před 6 měsíci +1

    Ternaries are only to be used with one line assignments/function calls. This should be the standard.

  • @canepaper967
    @canepaper967 Před 6 měsíci

    4:51 so like a guard clause...

  • @sasha759
    @sasha759 Před 4 měsíci

    thank you

  • @H4KnSL4K
    @H4KnSL4K Před 6 měsíci

    I think short and concise with proper formatting, where you can see the entire functionality in one reasonable component is much preferable to breaking up everything into an endless number of little components which all they do is an if check and then depend on a number of other components. I find trying to track down many components and how they fit together in my head much harder than reading a component that's a little bigger because it has a couple conditionals in it.

    • @H4KnSL4K
      @H4KnSL4K Před 6 měsíci

      Like isn't actually doing anything, itself! and you're repeating the names of these variables too. You could repeat this endlessly..

  • @domthedoer
    @domthedoer Před 6 měsíci

    6:57 was a flex and I’m offended

  • @heddshot87
    @heddshot87 Před 6 měsíci

    I've always hated ternaries in markup, never thought of doing it this way, much better!

  • @_jovian
    @_jovian Před 6 měsíci

    just use switch statements?
    switch(true) {
    case : return stuff
    }

  • @zwanz0r
    @zwanz0r Před 6 měsíci

    I would love if expressions in JS

  • @dakdevs
    @dakdevs Před 6 měsíci

    I agree with the top to bottom going into left to right, that is annoying to parse... The linter we use forces all JSX to be wrapped in parens with new line after start/before end. This way it's just reading top to bottom still even with the ternaries. Granted, I also would push back on nested ternaries. I'd rather just put the new ternary in a new component.
    Though, I am pretty interested in trying to do the return null flow you show here instead of ternaries in general.

  • @jvdl-dev
    @jvdl-dev Před 6 měsíci +14

    Amen brother. I've been a front-end developer for ~20 years and a staunch advocate for avoiding nested ternaries. I haven't really found any cases where I've preferred them. Ternaries in general can be hard to follow, consistent formatting across the JS/TS/JSX landscape at least makes them more palatable, but agree that nested is still awful. I would much rather see an "ugly" if/else chain that allows for easier to (mentally) parse code.

    • @DrPizza92
      @DrPizza92 Před 6 měsíci +2

      Been doing this for a long time too and I flat out can’t read nested ternaries.

    • @chrishyde952
      @chrishyde952 Před 6 měsíci

      Did ternaries even exist 20 years ago? Not being able to read valid code isnt an excuse to dismiss it. Its a preference

    • @clipesdaora
      @clipesdaora Před 6 měsíci

      ​@@chrishyde952 lua, c++, c..... nothing new

    • @jvdl-dev
      @jvdl-dev Před 6 měsíci +1

      @@chrishyde952 yes, ternaries have been around for much longer than that, in JavaScript they were part of the original language spec.
      While I agree that whether or not I use nested ternaries is a preference, I disagree with the premise that just because something is valid code it shouldn't be criticized if the way it is used makes it harder to read the code.
      I'm not _dismissing_ ternaries, but rather advocate for taking the most readable and understandable approach. Which IMO in many cases means that nested ternaries would be better off being rewritten.

  • @thegrumpydeveloper
    @thegrumpydeveloper Před 6 měsíci

    Agree especially now that undefined is fine.

  • @fexxix
    @fexxix Před 6 měsíci +10

    I think kotlin does this better because if-else can be used as expressions. For example:
    val number = 0
    val result = if number > 1 "greater than one" else "not greater than one"
    IMO that's just a better solution.

  • @yuriblanc8446
    @yuriblanc8446 Před 6 měsíci +3

    with angular you can just use ng container and ngIf ngFor without trading in clarity. With the new control flow syntax they may introduced the same issue.

  • @Mitsunee_
    @Mitsunee_ Před 6 měsíci

    is this just "make smaller less complex functions" but for components?
    Edit: Flatten = T[number] works for me just fine btw :3

  • @Gregorius421
    @Gregorius421 Před 6 měsíci

    10:42 C++ entered the chat: "Hold my beer"

  • @codycrank3465
    @codycrank3465 Před 6 měsíci

    When you wake up and it’s already April 🤣

  • @kpop2gm196
    @kpop2gm196 Před 2 měsíci

    and no this ain't some obscure esoteric lang - the function in the screeenshot is POSIX-compliant awk syntax

  • @5tevend
    @5tevend Před 6 měsíci

    I'm a bit concerned that Prettier is trying to justify that nesting ternaries is a good idea. the only case i ever see for a ternary is if you're doing a conditional spread in an object or array and then doing `{ ...myObject, ...(isThisThing ? { field: 'some value' } : { otherField: 'some other value' ) }` because although you can do ` ...( isThisThing && { field: 'some value' } )` that same doesn't work with arrays and you'll have to ternary arrays. So it just keeps that syntax similar.
    i do agree that if/else is messy, but that's why doing early returns with if checks is a lot cleaner than if/else blocks. A ternary is used it if it's a dichotomy, so just doing if (!notThing) { return } and then having your other logic continue below for me is a lot easier to read, and can often stop if/else nesting as well. And if it has a lot of conditions that's where switch statements or maps are useful. Because i totally agree having good legibility in your code is key, being able to come back into something months down the line and not feel like you're tiptoeing through cryptic but concise code is a godsend for refactoring, making changes, or just reviewing

  • @Awesomo4000
    @Awesomo4000 Před 6 měsíci

    1:52 If you put 2 !'s in front I'd expect the code to render the string "false". Doesn't it? That sounds like the actual bug.