5

I have var names = []; and want push there some string only if it's not empty. Is there way make it with some shorthand method in js?)

That i have now.

 if ("" != opportunityName) 
    {
    names.push(opportunityName);
    }

And that Don't wotk for me, it's push empty string.

names.push(opportunityName || "");
Maks Martynov
  • 460
  • 3
  • 18

1 Answers1

6

You can use short-circuiting:

opportunityName && names.push(opportunityName);

The right-hand operand will only be evaluated if the left-hand one is truthy.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Thx, that was so simple =) – Maks Martynov Jun 21 '13 at 14:51
  • It works, but it's barely shorter than `if (opportunityName) names.push(...);` and less readable... – LarsH Jun 22 '13 at 03:37
  • @LarsH It's shorter if curly braces are enforced by a code style, more so if new lines are added. I personally always use curly braces, so a short one-liner such as this is sometimes just what I need. – George Kagan Oct 04 '16 at 06:26
  • @timenomad: A valid point, in practice... such coding styles are not uncommon. I would say, though, that if a coding style enforces curly braces for the "then" clause of `if`, then in order to be consistent, it should enforce parentheses around the right-hand expression in this pattern where `&&` is used only for short-circuiting: `opportunityName && (names.push(opportunityName))`. However I haven't seen coding styles that enforce the latter. – LarsH Oct 04 '16 at 09:02