user473911
user473911

Reputation: 143

Most concise way to assign a value from a variable only if it exists in CoffeeScript?

Anyone knows of a more concise/elegant way of achieving the following?

A = B if B?

Thanks.

EDIT:

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

Answers (3)

Dieter Gribnitz
Dieter Gribnitz

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

deram
deram

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

mu is too short
mu is too short

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

Related Questions