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 || "");
0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thx, that was so simple =)
It works, but it's barely shorter than if (opportunityName) names.push(...); and less readable...
@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.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.