Hacker News new | comments | show | ask | jobs | submit login

Is it me, or did the author tack on a new topic regarding the use of && and ||?

The fact that they return the controlling operand is quite useful. Consider a situation where you want to check the property of an object, but don't know if that object is null:

  var foo = obj && obj.bar;
I find this much more readable than:

  var foo = null;
  if (obj) {
    foo = obj.bar;
You can accomplish the same thing with a ternary operator, but it's longer and, to my eyes, less scannable:

  var foo = obj ? obj.bar : null;
Also useful when setting optional parameters:

  function myFunc(foo, bar) {
    foo = foo || {};
    bar = bar || 'default_value';
(take care however: the empty string evaluates to false, as does [] and 0)

It's just you ;-). I love && and || being both short-circuiting (as in C) and value-preserving (as in LISPs, Perl, etc.). That's not the issue.

The issue is abusing && or || as the whole of an expression statement, instead of using if.

I can't speak for Brendan, but I generally think && / || are great for assignment, but otherwise it's code-smell.

    var foo = obj && obj.bar; // great
    !isActive && $parent.toggleClass('open'); // smelly
    if (!isActive) $parent.toggleClass('open'); // better

  if (!isActive) {
  } // best
Damian Conway of Perl fame wrote an excellent style guide for C in the early/mid 90s which I'm pretty sure explained why (I can't find my copy):

Programmer A:

  if (!isActive) $parent.toggleClass('open');
Programmer B:

  if (!isActive) 
Oh dear.

Yep, that's why I always demand that if you're not going to use curlies, you make it a one-liner.

    // okay
    if (!isActive) $parent.toggleClass('open');

    // not okay
    if (!isActive)
That way you know when you change it to two lines, you have to add curlies.

I believe HTML5 boilerplate implements the smelly pattern.


The problem here, I believe, is the abuse of && (or ||) to emulate conditional statements. Not expressions.

Your last parenthetical point is exactly why I'd avoid those uses of && and ||. Write a default_to() function (or a method in languages that allow methods to be defined on the null object) that wraps all those corner cases up.

Your post has made me realize however that I'm not sure if the language I'm reimplementing is meant to be value preserving in the case of those operators where an explicit corrosion from the a type to Boolean has been defined. Shows how often they're used like that in production code I guess.

[] as evaluated (an array literal) is truthy not falsy. Are you thinking of a context in which it is implicitly coerced to string?

empty array evaluates to true. :)

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