Samantha J Samantha J - 2 years ago 74
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) {
? 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);
} else {
var addPromise = self.wordFormAddSubmit(wf, key);

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

Answer Source

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 =.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download