Samantha J Samantha J - 5 months ago 10
Javascript Question

Do I need to use an "=" when using the ? : javascript shortcut?

Can someone tell me if this is valid javascript to do this:

if (wf.statusId == Status.Dirty) {
wf.createdDate
? promises.push(self.wordFormUpdateSubmit(wf, key))
: promises.push(self.wordFormAddSubmit(wf, key));
}


Would there be cases where this would not work correctly if createdDate was not defined?

Here's what this replaced:

if (wf.statusId == Status.Dirty) {
if (wf.createdDate) {
var updatePromise = self.wordFormUpdateSubmit(wf, key);
promises.push(updatePromise);
} else {
var addPromise = self.wordFormAddSubmit(wf, key);
promises.push(addPromise);
}
}


Also a related question. Would it be possible to use the same syntax with ? : to replace the need for the if () { } construct ?

Answer

Using = with ternary operator is not mandatory unless expr1 and expr2 are returning something and you want to save it in some other variable.

In your case, unless promises.push(self.wordFormAddSubmit(wf, key)) and promises.push(self.wordFormUpdateSubmit(wf, key)) are returning something that you want to save it a variable, there is no need for a =.