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 && ()
?
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 && ()
?
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()
}
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();
}