• python@lemmy.world
    link
    fedilink
    English
    arrow-up
    7
    arrow-down
    2
    ·
    12 days ago

    Javascript would have no problem with it. Semicolons are already kinda optional in there, and having tons of question marks in your code is also pretty normal. ie:

    input?.map(item => !!item?.name ? item : item?.toString() ?? "New Item")

    Just means: If the variable named “input” has a function named .map(), which is usually the case if it’s an array, you go through that array and transform its elements in the following way:

    • is your element an object that has the property “name” and that property isn’t undefined, null or 0? (the “!!” is a double negation that would force undefined, null and 0 to evaluate to false through type coercion)?

    • if yes ( the syntax " ___ ? ___ : ___ " is a shorthand for an if-else statement) then just add that whole item to your output array.

    • if not, try to call the .toString() function on your item. If that works then that’s your result, if not then your output is the string “New Item” ( the “??” is called the nullish coalescing operator - if the left side of the ?? evaluates to undefined or null, it takes the right–hand side value instead. The “?.” part is called optional chaining and will evaluate to undefined if you try to call a function that doesn’t exist on that type)

    • oh yeah, and if input isnt an array to begin with and doesn’t have a .map() function? We just do nothing and move on without complaining. JS truly does not give a fuck.

    • dave@feddit.uk
      link
      fedilink
      English
      arrow-up
      6
      ·
      12 days ago

      You missed a ‘?’ I think you meant:

      input?.map?.(item => …

      • python@lemmy.world
        link
        fedilink
        English
        arrow-up
        3
        ·
        12 days ago

        oh, you’re right lol
        The first ?. after input would be more more of a safeguard against input being null/undefined and the .map not existing on it would have to have another ?.

    • Sunkblake@lemmy.world
      link
      fedilink
      English
      arrow-up
      3
      ·
      12 days ago

      Yeah c# has null propagation and null coale aswell. But I imagen Greeks learning programming having fun with it for a little while.