1

Here is the function I am working with. I actually found it in React Native documentation :

var testFunction = function(word) {
  return word && '';
}

Here is how I am using this function :

var testWord = testFunction("Alex");

The final value of testWord, returned by testFunction, is "".

I would have expected the returned value to be either true or false, as the result of the && expression. However the value is a string of value "".

Could someone explain the logic behind this ?

Alexandre Bourlier
  • 3,698
  • 4
  • 38
  • 71
  • 1
    please see related topic [http://stackoverflow.com/questions/17200315/logical-operator-and-two-strings-in-javascript](http://stackoverflow.com/questions/17200315/logical-operator-and-two-strings-in-javascript). You can see also a clear explanation [here](https://en.wikipedia.org/wiki/Short-circuit_evaluation) – morels Jul 14 '16 at 13:43
  • @morels Short-circuiting and returning of an operand instead of a boolean are rather unrelated. – deceze Jul 14 '16 at 13:56
  • `return word && '';` is a sc evaluation and in linked wiki page you can exactly read that the expected value is the one is got by OP `JavaScript`, operands: `&, |`, expected vaue: `&&, || Last value` – morels Jul 14 '16 at 13:58

1 Answers1

5

The && evaluates as the right hand side if the LHS is true, otherwise it evaluates as the LHS. It doesn't evaluate as a boolean.

0 && 1 // 0 because 0 is not true
1 && 0 // 0 because 1 is true
1 && 2 // 2 because 1 is true
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205