0

Sometimes, when reading Code written by others, I come across lines of code that I do not understand, for example this one:

 var acceptBtn = document.getElementById('saveBtn');
 (acceptBtn) && (acceptBtn.disabled = false);

What exactly is the meaning of the second line and why is it abbreviated like this?

Lokomotywa
  • 2,455
  • 7
  • 40
  • 66

3 Answers3

3

It's shorthand for "if acceptBtn is not "falsy", then set it's disabled property to false".

ie:

if(acceptBtn){
    acceptBtn.disabled = false;
}
tkone
  • 20,822
  • 5
  • 51
  • 77
tymeJV
  • 102,126
  • 13
  • 159
  • 155
  • 1
    Not just `null` values, but anything that evaluates to `false` through type coercion. So `0`, `undefined`, `""`, etc – tkone Oct 30 '14 at 13:27
3

It's a strange syntax, but it's shorthand for:

if(acceptBtn)
    acceptBtn.disabled = false;

I would personally never use it, though.. Bad readability.

Thor Jacobsen
  • 8,127
  • 2
  • 27
  • 26
2

The second line takes advantage of the fact that boolean operations in Javascript short-circuit, that is to say if the first part evaluates false then the second part never executes.

It also takes advantage of the fact that javascript can use truthy/falsey values in boolean expressions.

Therefore the second line says, that if acceptBtn is falsey (possibly: null or undefined) then go no further, otherwise set the disabled property to false.

It stops javascript running in to the equivalent to a null-reference exception.

Jamiec
  • 128,537
  • 12
  • 134
  • 188