Alan Alan - 5 months ago 11
Javascript Question

Can I use a ternary opertator when there is a "return" from the conditions?

I am trying to call a procedure to go to another state and have this return. Previously I had coded it like this:

if (self.word && row.wordId == self.word.wordId) {
return this.$state.go('r.s.s.a.w.w.edit', {
subjectId: self.sus.subject.id,
wordId: row.wordId
});
} else {
return this.$state.go('r.s.s.a.w.w', {
subjectId: self.sus.subject.id,
wordId: row.wordId
});
}


Now I am coding it like this:

return self.word && row.wordId == self.word.wordId
? self.$state.go('r.s.s.a.w.w.edit', {
subjectId: self.sus.subject.id,
wordId: row.wordId
})
: self.$state.go('r.s.s.a.w.w', {
subjectId: self.sus.subject.id,
wordId: row.wordId
});
}


Can someone confirm if this is a valid way to do this or should I have returns before the self.$state.go ?

Answer

Your examples are identical, as far as I can see. However, I prefer the first one's readability.

In your specific case (not as a general solution), I'd probably write this:

var whereNext = self.word && row.wordId == self.word.wordId
  ? 'r.s.s.a.w.w.edit'
  : 'r.s.s.a.w.w';

return this.$state.go(whereNext, {
  subjectId: self.sus.subject.id,
  wordId: row.wordId
});

or even

var edit = self.word && row.wordId == self.word.wordId ? '.edit' : '';

return this.$state.go('r.s.s.a.w.w' + edit, {
  subjectId: self.sus.subject.id,
  wordId: row.wordId
});
Comments