3

Can anyone explain to me what is the difference between these two statements and why the second one does not work and the first one does:

  1. if (finalWord.length > 140) return false; else return finalWord;

  2. (finalWord.length > 140) ? false : finalWord;

Dito
  • 915
  • 2
  • 10
  • 26
  • 4
    They do the same thing. The second one doesn't work because you are not returning anything – bugs Oct 18 '18 at 11:04
  • 2
    You miss the `return` statement in the second example. It should be `return (finalWord.length > 140) ? false : finalWord;` – Weedoze Oct 18 '18 at 11:04
  • The second version is missing the return statement. It should be `return (finalWord.length > 140) ? false : finalWord;` or `return finalWord.length > 140 && finalWord;` – AndreasPizsa Oct 18 '18 at 11:05
  • Also, see [Conditional operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) – bugs Oct 18 '18 at 11:06

1 Answers1

4

It looks, you miss the return statement.

return finalWord.length > 140 ? false : finalWord;

You could shorten it to

return finalWord.length <= 140 && finalWord;
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • I am so stupid :)) I thought that the return statement was implicit when using ternary operator. thanks – Dito Oct 18 '18 at 11:07
  • 1
    @Dito if it was, then you wouldn't be able to write `var myVar = someVariable == otherVariable ? "yes" : "no";` – VLAZ Oct 18 '18 at 11:08