DEV Community

Cover image for JS && Operator Quirks: Better Approaches?
SREY
SREY

Posted on

JS && Operator Quirks: Better Approaches?

Hello everyone! It's been a while, and I hope you're all doing well. Reflecting on the past year, I'm thrilled about the strides I made in my writing journey, sharing insights and experiences through my blogs. Here's to more growth and compelling stories in the coming year! Also Happy New Year!


Without further ado lets roll with the title above, Recently on the internet I saw Theo explaining what's wrong with the using of && operator in js while returning inside of a functional component.

Let me explain, What I mean't above by my code :

 export default function App() {
  const people = ["deliSrey", "deli", "Srey"];
  return (
    <div className="App">
      {people.length
        && people.map((_people, index) => {
            return <li key={index}>{_people}</li>;
          })}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

It result's something like this:

code-snippet-result


You might think What's wrong in it There is nothing wrong in it, but also there is something not correct about It, here it could result in a potential bug if you see in a hindsight

For Example If there is nothing inside the people array list and hence the people.length is 0 which by default returns 0
rendered on the screen something like this, Here is the code and result attached:

code-snippet

code-snippet-result


Above is how ternary operator replaced by && operator looks like, which almost make sense but not in case of nested ternaries:


With Nested Ternary :

code-snippet


But now What should we do instead, Should we go towards ternary operator, I mean it is a praticed way but in the same video Theo explained an interesting way to do it. When there are way more ternary operators nested for checking out multiple conditions, which create a bitter mess and the code is almost unreadable, we can break it into Components,That's where the beauty of React lies, split the nested stuff into the functional components

here's how it is :

code-snippet

code-snippet-result


In case where the people array list is empty :

code-snippet

code-snippet-result

Here you can see how the readability and flow of the code is maintained more accurately and hence while working in a team It makes perfect sense to maintain the code quality where the code can be easy to debug and can be easily improved with new features.

That's all in this blog, I guess If you have already came up til here, You might also try smashing your thumb on follow and like button Trust me it helps my blog to reach more people like you and me!

Also Special Thanks to the W Engineer Theo For putting this in his video which inspired me to write a blog on it as well also here is the link to the video

Until then it's a huge goodbye fellas!

Top comments (0)