Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

While I endorse the argument for coding for readability (all things being equal), I don't agree with his example. I find the && syntax in javascript completely readable.


I find it readable if you're trying to test both sides of the && to be true -- if(foo() && bar()){ // do this }

However, the way it's written in the article, the intent is to merely test foo() and then execute bar() if foo() returns true. Even though I'm familiar with &&, it took me a minute to understand this as well. I'd be eqaully annoyed seeing this in production code.


I'm with the GP on this one... Readable code is very important. Using the short-circuiting property of && doesn't decrease readability in most cases (unless someone isn't familiar with the language, or the concept of using short-circuiting for flow control).


I've always found the Perl

foo() or die();

idiom to be quite readable. And if you're familiar with that, this is a pretty straightforward extension.


It's a common idiom in many programming languages.


I disagree -- it probably is not immediately understood by most programmers.

The main flaw of the technique is that the author uses the '&&' not as a logical operator (the intuitive use) but as a conditional operator.

'&&' is the 'Logical AND'. The statement "foo() && bar();" just doesn't make initial sense, because the logical result of the expression is thrown out.

After thinking this, the programmer probably will realize that the functions are actually called to evaluate the expression. And then finally (hopefully) the programmer realizes that they are evaluated short-circuit.

So, the code may be functional but it is not very readable.


"the expression evaluates to true if both return True, but then why is the result thrown out"

Actually, the result is not thrown out: the && operator produces the value of its first operand if the first operand is falsy, otherwise it produces the value of the second operand.

For what it's worth, there's also a procedural reading of "foo() && bar()" along the lines of "fill out this form AND win a prize!".


I wrote 'thrown out' because the statement is "A && B;" -- the result is unused due to the terminating semicolon.


I agree. As long as the example idiom is something that's used consistently throughout the code it's all good. Even if you're new to the code and don't immediately get it, you will instantly recognize it the second and third time around.


This is pretty straightforward and intuitive, so I agree with this reply. Maybe it's because of the equivalents in lisp (I tend to use lisp a lot):

  (if (foo) (bar))
equals to

  (and (foo) (bar))




Consider applying for YC's Winter 2027 batch! Applications are open till November 2.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: