Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 943
user473911 Avatar asked Jun 16 '12 00:06

user473911


People also ask

How do I declare a variable in CoffeeScript?

In JavaScript, before using a variable, we need to declare and initialize it (assign value). Unlike JavaScript, while creating a variable in CoffeeScript, there is no need to declare it using the var keyword. We simply create a variable just by assigning a value to a literal as shown below.

What happens when you assign a value to a variable that has not been declared it will automatically become a global variable?

Automatically Global If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. This code example will declare a global variable carName , even if the value is assigned inside a function.

What happens when you assign a value to a variable that has not been declared?

If you assign a value to a variable that you have not declared with var , JavaScript implicitly declares that variable for you. Note, however, that implicitly declared variables are always created as global variables, even if they are used within the body of a function.

How do you check for undefined in CoffeeScript?

if (typeof MyVariable !== "undefined" && MyVariable !==


2 Answers

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/)

like image 123
mu is too short Avatar answered Sep 21 '22 17:09

mu is too short


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.

like image 44
deram Avatar answered Sep 24 '22 17:09

deram