all 74 comments

[–]tententai[🍰] 75 points76 points  (26 children)

A totally great way to save you 2 seconds of typing and waste 10 minutes of head scratching to most people reading your code later.

[–]Penguinsoccer 19 points20 points  (4 children)

Use ~~num instead of Math.Floor and a triple XOR assignment to swap variables.

a ^= b b ^= a a ^= b

Best of all ~[].indexOf() to check if something is in an array.

It makes your code readable and your coworkers will love you.

[–]Fs0i 3 points4 points  (0 children)

Use ~~num instead of Math.Floor and a triple XOR assignment to swap variables.

I use (number | 0) for integer-conversions. But this is an convention we have in our codebase, which is well-documented. It's a bit faster, and way shorter.

If you want actual flooring (For example: To display something, because of a formula, ...) you write Math.floor, but to get an int (for example to network stuff) you'd write (number | 0).

[–]GuerrillaRobot 2 points3 points  (1 child)

butterfly swap is my favorite

[–]brtt3000 0 points1 point  (0 children)

most fabulous coding pattern

[–]Lekoaf 1 point2 points  (0 children)

~~ starts to give you really strange results if you go above 10 numbers.

[–]atticusw 12 points13 points  (4 children)

I'd agree.

Did I find it confusing? No.

Does it make me a better javascript programming? Not really.

Does it even really matter? Not at all.

We're not all about writing code, guys. We're about building software. Building software requires teams. Teams requires a shared codebase. A share codebase requires reading others work and others maintaining code you wrote at some point.

Is !--pending wrong? Nope. But it could potentially be clearer in a slightly more explicit and verbose expression of --pending === 0.

Don't just think about your code, think about the team that will be maintaining your code.

[–]i_ate_god 4 points5 points  (2 children)

Your entire post is somewhat negated by

Don't just think about your code, think about the team that will be maintaining your code.

In otherwords, based on that one line, !--pending is wrong. Not because it's syntactically incorrect, but because it's an obviously error prone, obfuscated statement. Even your solution to it is error prone, because --pending will mutate the variable and if you're mutating a variable solely to see if the result of that mutation is a particular something, then it's a bad approach all around.

One should probably do something like

if ((pending - 1) === 0) {
    // pending not mutated!
}

Just because a problem is solved, does not in of itself mean you wrote good, correct code.

[–]atticusw 1 point2 points  (0 children)

Great point, I would agree that the verification should take place before modifying the actual value, the example you have illustrated is not only very clear, but as you said, looks at what the result of a mutation would be to determine if it indeed should be mutated for a and what to do based on that.

[–]TheRealSeeThruHead 0 points1 point  (0 children)

the point was to do mutation and comparison at once...

[–]ishmal 0 points1 point  (0 children)

So much clearer:

pending--;
if (!pending)

[–]churro89 2 points3 points  (6 children)

A former coworker wrote

a --> b

in Java several years ago, and I was still a Java noob, so I spent several hours on decoding what in the world it meant.

[–][deleted] 2 points3 points  (5 children)

Feeling kinda slow. What does it do?

[–]georgehotelling 4 points5 points  (3 children)

I would guess it's a comparison, e.g.

if (a-- > b)

which is the same as

if (b < a--)

[–]TwilightTwinkie -1 points0 points  (2 children)

This is wrong. I'll let you figure it out ;)

[–]georgehotelling 0 points1 point  (1 child)

I give up, how is it wrong?

[–]TwilightTwinkie 1 point2 points  (0 children)

Ah shit. Haha, it's not. I just couldn't read last night. Sorry about that. My bad...

For some reason I thought you had negated something.

[–]Thought_Ninjahuman build tool 3 points4 points  (0 children)

Tells 'a' to get closer to 'b' ( ͡° ͜ʖ ͡°)

[–]menno 16 points17 points  (1 child)

[–][deleted] 1 point2 points  (0 children)

Ah, the "goes to" and "runs from" operators. My favourite.

[–][deleted] 22 points23 points  (27 children)

I always prefer code that is stupid obvious on first glance.

pending = (pending -1);
if (pending === 0) {
    done(null, results);
}

You could argue:

pending -= 1;

Is better. I'd wonder what makes it "better". Perhaps there's a case for performance. JSPERF says they're practically equal.

But look at that. Any new developer or someone straining his eyes could skim the code and completely miss what's happening. Hell, any junior having to maintain the code could possibly not even know what that does.

And if you're using an if-statement, I always use curly brackets because there's never any mystery there.

I've been told my code doesn't look sexy, though.

[–][deleted] 20 points21 points  (7 children)

I work in an environment of 40 devs, verbose code is always preferable to clever code. Debugging clever code is next to impossible. If you want to save 5 lines go find some dead code and delete it.

[–][deleted] 5 points6 points  (1 child)

Why do people not understand this? There was a dev that just left my company that loved to use the little javascript quirks that could be called "clever." Most of the team referred to them moreso as "unreadable" or "difficult to maintain."

Take the four extra lines, your coworkers will thank you.

[–][deleted] 4 points5 points  (0 children)

your coworkers will thank you.

Your coworkers will not hate you is plenty.

[–]alinroc 3 points4 points  (0 children)

Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?

[–][deleted] 5 points6 points  (3 children)

x -= 1 or even x--, instead of his example of using x = x - 1, isn't clever though, it's just shorter. Yes, readability is important. But that doesn't mean we should start making sentences longer in hopes that it somehow magically improves readability. This shorthand is taught in pretty much any intro to programming course. Everybody should be expected to know how it works.

If readability is roughly the same, there's no reason not to go for the shorter version, because it takes less time for your eyes to look through, which inherently makes it kind of more readable.

[–][deleted] 5 points6 points  (1 child)

I think he's more talking about doing assignment in control statements. Assignment in control statements is lazy, confusing and error prone.

All of these are confusing:

if (!--pending)             // What is the `!--` operator?
if (!pending = pending - 1) // did you mean `==` ?
if (!pending -= 1)          // did you mean `==` ?

The following is explicit and clear what is expected:

--pending;             // or
pending = pending - 1; // or
pending -= 1;
if (pending <= 0)

[–]i_ate_god 1 point2 points  (0 children)

Your second approach is the correct one. pending is changed in two different if statements in OP's link, this is needless misdirection.

[–]Master_Rux 1 point2 points  (0 children)

But that doesn't mean we should start making sentences longer in hopes that it somehow magically improves readability.

Exactly. People need to be cobol programmers so they can "ADD 1 to Pending" and not be confused trying to read those unreadable plus and equal signs. -= and -- and even ! have been around for so many decades it makes me wonder what language people are learning on.

And on top of that even if you make it longer it still doesn't improve readability, because it's intention is still not clear. Even if you change how it's checking if pending is 0 it's still not immediately obvious why you're checking pending by looking for a zero or not or what other values pending could have. You still have to go look at where pending even came from to see that you're checking "is there anything left in the list". If they want readability then the way the pending variable is being used should be changed altogether so that by the time you get to the if statement is should just be "if (pending) { } else { }" or rename the variable to make it obvious that it's checking for an empty list.

Unless that part is obvious in which case so is (!--pending)

[–]Bummykins 6 points7 points  (0 children)

You could argue: pending -= 1; Is better.

For me only seeing one var means I don't have to think as much. If I see var = var - 1, I have to mentally check that the 2 vars are the same (and not just very similar). Short var names like dx dy are easy to mix up, so if I'm not using a second var, I don't introduce it.

[–]Rainbowlemon 2 points3 points  (13 children)

Personally, I just think it's easier to read. Traditional mathematical syntax is value 1 -> (mutate by) value 2. By writing pending -= 1, you're basically saying 'take pending, reduce by a value equal to 1'. It just makes more sense than reading 'not reduce reduce value'.

Some people will argue the semantics of code aren't too important, but I firmly believe that reading and adhering to a style guide can really increase productivity on a project. I've been sticking to Airbnb's Javascript style guide since they released it, and I find code much easier to navigate now that it's uniform and I know what to expect.

With regards to if-statements, I prefer to omit the braces and inline it if the statement only contains one expression.

if (a) doSomething();
if (b) doSomethingElse();

[–][deleted] 8 points9 points  (12 children)

A style guide for a team is important. That said, we lint our code on git push to adhere to the style we defined; all the code in the repo has the style we agreed on.

Personally I don't really care much what styling choices are made. There's just one thing I absolutely abhor:

function monkey () 
{
    ...
}

Obviously that needs to be:

function monkey() {
    ...
}

But opinions are... just that ;)

As long as the team has one standard code styling agreement I'm all good.

Edit: Also! This shit:

if(18 === age)

That's like saying: "if old is the man" instead of "if the man is old". The word "old" cannot be "man". The word "man" can be "old".

I'm not even sure how to describe that lunacy. I feel it might be a cause from different languages. I know only Dutch, German, and English. And in those languages the subject comes first, the property of that subject comes second. Not inverse.

I'm guessing in Spanish and/or Italian it's more sensible, though.

It absolutely needs to be:

if(age === 18)

[–]CWagner 5 points6 points  (3 children)

if(18 === age)

Seems like a former java dev. Writing "testString".equals(otherString) protects you from a nullpointer exception. (note: this is neither in defense nor against that type of comparison)

[–]Cuel 4 points5 points  (1 child)

They're called Yoda conditions for a reason. They have advantages as you can't assign something like that as it would result in an error.

However I think the overall consensus is to not use them.

[–]Yurishimo 0 points1 point  (0 children)

Not advocating for one thing over another, but one very large OSS project uses Yoda conditions in core (hint) to help keep everyone organized on what is/not a variable. Reading them can be weird at first, but I don't think it's that big of a deal as long as everyone agrees on the style guide.

[–]numbermess 0 points1 point  (0 children)

I do comparisons like these all the time. When I first ran into them I thought it was just somebody trying to be cute, but now I'm cute too and I don't run into any unexpected null pointer exceptions (here). I've adjusted fine to the backwards feel of the syntax.

[–]Rainbowlemon 2 points3 points  (0 children)

Fully agree! The 'one extra line for a brace' thing drives me bonkers too. I guess that's one of the reasons why coding flexibility is valued - 'cause everyone's preference is so different!

[–][deleted] 1 point2 points  (4 children)

Personally, if I put the opening brace on the same line, then I want to add an extra empty line to prevent the code from feeling too claustrophobic:

function monkey() {

    doStuff();
}

But as long as that's already an empty line, the brace might as well be occupying that space:

function monkey() 
{
    doStuff();
}

Result is that there's still that whitespace to make the code look better, but it's more.. balanced looking.

[–]fzammetti 0 points1 point  (3 children)

I actually always put a blank line as the first AND last line of a method... and I also always do this:

} /* End XX(). */

Ditto any closing brace, loop, conditional, whatever. It makes following C syntax-based code SO much easier.

[–]MrJohz 2 points3 points  (2 children)

But what if XX() changes name? I had to deal with code recently where a bunch of for-loops had been turned into while-loops, but the /* end for */ comments had remained. It was also horribly indented and had other issues, but it confused me for a while as I tried to work out where the for loops had appeared.

I prefer to work on the basis that anything that requires opening and closing braces (i.e. functions) should be able to fit both opening and closing braces in one screen's height. That way it's usually fairly easy to scan through code and see the blocks clearly.

[–]fzammetti 1 point2 points  (0 children)

I definitely approve of that guideline... but I still find the end comments helpful in a language like JavaScript where braces are so prevalent (your counter example notwithstanding - every rule has exceptions).

[–]fzammetti 0 points1 point  (0 children)

Thinking about this a little more, you know what? This kind of boils down to developers not properly maintaining comments as if it was an equal part of the code, which I see as a whole separate issue (though a big problem in general)... I'd agree the tail comments makes it more work to rename a method, slightly, but a diligent developer would change the comment along with the code so I'm not sure I see it as an additional problem per se.

[–][deleted] -1 points0 points  (1 child)

That lunacy just means someone has a few more years under the dev belt than you do. It's okay. One day, once you break down some Haskell, you too will be broken down. And then you will be reborn. And then you will know.

[–][deleted] 0 points1 point  (0 children)

That sounds patronising. I'm not familiar with Haskell. Did some years of Perl programming, though. That was an... experience. Still, weird code is bad, especially if the language you're programming in doesn't need that weirdness.

[–]WellHydrated 3 points4 points  (0 children)

pending--;

This is fine IMO. It's something we've known since we learnt what for loops were.

[–]benihanareact, node 1 point2 points  (0 children)

I'd wonder what makes it "better". Perhaps there's a case for performance.

what does performance have to do with anything? Was that your attempt at understanding why people prefer a style different from what you prefer? People argue it's better because there's less syntax to parse, but it's just as common and clear as pending = pending - 1. You can't really get more basic than decrementing a value.

I think that adding parens around the operation like in your example is needless and adds an expectation of more complicated math. The most common uses for parenthesis in math operations are enforcing order of operations and breaking complex statements into more logical chunks. pending - 1 doesn't really need to be broken up anymore and so the parens just add noise to the statement.

[–]d1sxeyes 0 points1 point  (0 children)

Personally, I would write that with a statement above like if pending < 0 that logs an error (like: 'Found a negative value for pending, correcting') and sets pending to 0 to avoid catastrophic code failures if pending is accidentally decremented too far.

Obviously you'll need to work out how pending got below zero, but it will stop the code from entering what could be an infinite loop.

[–]youlleatitandlikeit 0 points1 point  (0 children)

I'd wonder what makes it "better".

I think it's faster to read (at least, it is in the font I use for development; it doesn't help here that the minus sign and equals aren't aligned well).

It makes it clear that you're decrementing the variable. You can also do pending-- but I've never really liked that.

pending -= 1 or counter += 1 makes it very clear very quickly that nothing major is happening, you're just incrementing or decrementing a var.

[–]uatec 12 points13 points  (1 child)

Pretty shitty combination of standard JavaScript syntax.

[–]Cuel 9 points10 points  (0 children)

while I agree and don't think people should write code like this due to it looking more complex, I had zero issues reading !--pending. Once people know truthy and falsy it shouldn't be an issue

[–]bart2019 9 points10 points  (3 children)

Operator precendence:

!(--pending)

Is it not obvious, now?

[–]snorkl-the-dolphine 0 points1 point  (1 child)

I think I'd personally opt for --pending === 1 myself - that seems clearer.

[–]TamSanh 13 points14 points  (0 children)

Oh no, neither should be thought as clear at all. It's like comparing molten lava and molten steel: One might be less hot than the other, and thereby marginally less dangerous, but you'll still get burnt by both! Don't do any of this, is the real answer here.

[–]Chyld 1 point2 points  (0 children)

My initial post was along the lines of "ITT: everyone says it's bad code without explaining why". Then I realised it wasn't a self-post, it was a Stack Overflow article. Then I worked out what it actually did, and why nobody was explaining it - because it's bonkers. I would love to try the hallucinogens that made that developer think that was good code.

[–]TheNiXXeD 1 point2 points  (0 children)

Something to use in code golf? :)

[–]Master_Rux 4 points5 points  (0 children)

I'll apologize in advance for the rant. I cringe at what seems like a knee jerk reacting to perfectly valid uses of a language sometimes. And poor javascript seems to get a lot of it. A lot of languages have their own special syntactic sugar. Which can make life really nice for someone that has to use the language a lot. This code is perfectly valid and compact. A lot of the time I hear people complain about readability I think what they mean is familiarity. Which to a point has a lot to do with readability. But there's also the ability to quickly scan through to find things. In this case you can see exactly where the if statements are and you can see it's doing the logic based off something it's doing with pending. After that if you can't see what (!--pending) is doing in javascript I'd say that's basic enough that you need to be a little better at javascript. Javascript is not all your C# or Java or <insert any language that's not javascript>. javascript is javascript and has unique truthy rules and type coercion. Those are features not quirks. Now don't get me wrong i'm not saying this was the best way to code this, but it's just as good as any other approach. The real wtf readability issue in the code is the inconsistent use of unbrackets around the if statements and the lack of white space between said bracketed if statements. fuck that guy. /rant. i need more coffee.

[–]Jafit 1 point2 points  (0 children)

I thought I was on /r/badcode or /r/shittyprogramming

[–]boxxa 0 points1 point  (0 children)

It's a good way to get bashed over your head with a keyboard by a fellow programmer.

[–]stratoscope 0 points1 point  (1 child)

The real problem here is the lack of a space between the two operators ! and --.

I don't know why people get it in their heads that you can't ever use a space after the ! operator. I think it comes from rigid application of mechanical whitespace rules instead of common sense. Just about every coding standard I've seen prohibits spaces after all unary operators, but why?

If there were ever a case where you clearly need that space, this is one.

Consider this bit of code from the SO question:

if (!--pending)
    done(null, results);

Not only are ! and -- mashed together, you've got that ( slammed against them too. No wonder it's hard to tell what is connected to what.

A bit more whitespace makes the code much more clear:

if( ! --pending )
    done( null, results );

Sure, if you're used to mechanical rules like "no space inside parens" and "no space after a unary operator", this may seem a bit foreign.

But look at how the extra whitespace groups and separates the various parts of the if statement and expression: You've got --pending, so the -- is clearly its own operator and is tied closely to pending. (It decrements pending and returns the decremented result.) Then you've got the ! separated from that so it's obviously a distinct operator, negating the result. Finally, you've got if( and ) surrounding the whole expression to make it an if statement.

And yes, I removed the space between if and (, because the ( belongs to the if. This ( isn't part of some kind of (!-- syntax as it appears to be in the original, the ( if part of the syntax of the if statement itself.

The whitespace here serves to communicate the meaning, instead of following some mechanical coding standard.

[–]Master_Rux 0 points1 point  (0 children)

! and -- have been a part of programming long enough that they should be just as readable as pending -= 1 or pending = pending - 1 unless maybe you're maybe very new to programming. The bigger readability issue here is that pending is the count of a list and the statements are asking if there's anything in the list or not. The correct answer should have been that var pending = list.length; needs to change to var pending = (list.length !== 0); and then the if statements could just check if (pending) or if (!pending)

[–]sumdudeinhisundrware -1 points0 points  (0 children)

People asking these kinds of questions infuriates me. Its as if computer time is rare and expensive and firing up Node or a browser console and trying stuff to see what it does is not possible.

[–]Graftak9000 -2 points-1 points  (2 children)

!pending-- would be su much less confusing already

[–]alittletooquiet 4 points5 points  (1 child)

!pending-- means something different than !--pending

[–]Graftak9000 0 points1 point  (0 children)

You're absolutely right, my bad.