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,624
  • 8
  • 44
  • 73

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
  • 22,092
  • 5
  • 54
  • 78
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • 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,621
  • 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
  • 133,658
  • 13
  • 134
  • 193