DEV Community

Discussion on: JavaScript pro programmer vs newbie programmer

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

I'll add, in any bracketed language, no-bracket conditionals are an utter style sin unless they're on the same line, simply because of how easy it is to not notice the lack of brackets and add another line!

BAD:

if (condition)
    console.log('Yes')
else
    console.log('No')

You're now at high risk of forgetting those brackets are missing and just adding another line:

if (condition)
    console.log('Yes')
else
    console.log('No')
    haltAndCatchFire()

Oops, why is my program crashing all the time now? Missing brackets. I just ninja'd myself right into a brick wall.

However, what you showed is usually acceptable...

if (condition) console.log('Yes')
else  console.log('No')

Regardless, this also becomes a "cleverness" trap, as that "pro" code can easily become unreadable, even respecting the one-line rule. Terrible example:

if (condition) doSomeFunction(thatHas, anUngodly, numberOf, arguments, passedTo, it, pleaseMake, itStop)

Heaven help you if you get a lambda or iteration involved.

After functionality, readability and maintainability matter above all else!

The real difference between a newbie and a pro is not found in how clever the code can be; it's in knowing when to use the syntactic sugar, and when to stick with the "boring" conventions for the sake of good code.

P.S. I'm a C++ (and Python) dev, not a JS dev, but the style rules are pretty much universal across all ALGOL-inspired languages.

Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited

Another one of those "pro-dev" things that can be a bit confusing is this for only positive conditionals:

     condition && console.log("Was here")

I can never make my mind up if I like it - I do write that when debugging, but pretty much never in "real code"

It works with everything apart from assignment which requires brackets

condition1 && condition2 && (something = somethingElse)

Again not advocating, but it is out there in people's code.

Thank goodness of optional chaining though (thanks babel) so my if's can go from:

   if(someObject && someObject.subObject&& someObject.subObject.value > 299) {
     //whatever
   }

to

   if(someObject?.subObject?.value > 299) {
   }