1

I have following line of code in javascript:

q && (c = q === "0" ? "" : q.trim());

WHat does it mean? I understand that c is equals either empty string or q.trim() result, but what does mean q && ()?

Jevgeni Smirnov
  • 3,787
  • 5
  • 33
  • 50

3 Answers3

5

JavaScript optimizes boolean expressions. When q is false, the right hand side of the expression doesn't matter for the result, so it's not executed at all. So this is a short form of:

if( q ) {
    c = q === "0" ? "" : q.trim()
}
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
3

It is a guard against undefined/null/false variables.

If q is not defined, false or set to null, the code short circuits and you don't get errors complaining about null.trim()

Another way to write that would be:

if(q) {
  c = q === "0" ? "" : q.trim();
}
Kyle
  • 21,978
  • 2
  • 60
  • 61
0

You can use this kind of clause to check wether q is defined.

kisp
  • 6,402
  • 3
  • 21
  • 19