Reputation: 143
Anyone knows of a more concise/elegant way of achieving the following?
A = B if B?
Thanks.
I'm looking for a solution that references A and B once only. And would compile to
if (typeof B !== "undefined" && B !== null) { A = B; }
or something else similar.
To have this short helps have the following a bit more readable:
someObject[someAttribute] = (someOtherObject[someOtherAttribute] if someOtherObject[someOtherAttribute]?)
That is the motivation for my question.
Upvotes: 14
Views: 6631
Reputation: 5208
Not sure about Coffee Script but you can use the OR operator for this in regular javascript like so:
a = b || a
Upvotes: 2
Reputation: 31
Maybe something like:
A=_ if (_=B)?
expanded:
if ((_ = B) != null) {
A = _;
}
This will overwrite A with what ever is in B, but only if it is not null, referencing both only once.
Upvotes: 3
Reputation: 434665
You could say:
a = b ? a
For example, this:
a = 11
a = b ? a
console.log(a)
b = 23
a = b ? a
console.log(a)
will give you 11
and 23
in the console (demo: http://jsfiddle.net/ambiguous/ngtEE/)
Upvotes: 21