0

function parseData (data) {
  return (data && JSON.parse(data)) || [];
}
var arrayOfObjects;
var defaultValue = parseData(arrayOfObjects);
console.log(defaultValue); // "[]"

arrayOfObjects = [{id: 1}, {id: 2}];
var stringified = JSON.stringify(arrayOfObjects);
var parsedValues = parseData(stringified);
console.log(parsedValues); // "[{id: 1}, {id: 2}]"
console.log(Array.isArray(parsedValues)); // "true"

I understand why passing undefined returns the fallback empty array.
But why does passing a defined value to parseData() return an array instead of a boolean?
Wouldn't the logical AND operator in data && JSON.parse(data) coerce and combine both operands to true?

remy-actual
  • 724
  • 7
  • 19
  • 2
    What makes you think that `expression || expression` does not return a boolean while `expression && expression` does? – Ivar Dec 03 '18 at 18:48
  • Funny enough a very similar question was asked just this morning: https://stackoverflow.com/questions/53597233/js-object-null-checking-weird-js-problem – Tyler Roper Dec 03 '18 at 18:58
  • @Ivar because `||` passes if either expression evaluates to true, but `&&` requires both expressions to evaluate to true. How does JavaScript combine data types? In this example, first expression is an Array and second expression is a string. – remy-actual Dec 03 '18 at 22:12
  • 1
    @remyActual It doesn't combine it. From [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators): "_`expr1 && expr2` Returns expr1 if it can be converted to false; otherwise, returns expr2._" In your example `data` can be converted to `false`, so it returns `data`'s value which is `undefined`. – Ivar Dec 03 '18 at 22:15
  • @Ivar Gotcha, thanks. That's essentially what I wanted to know. – remy-actual Dec 03 '18 at 22:20
  • @remyActual The `||` works pretty much the same only in that case it returns `expr1` if it is true instead of false. That is why you can use the "fallback empty array" because if the left hand side is falsy, it returns the right hand side. Because they work so similar, I wondered why you thought they worked differently, hence my first comment. – Ivar Dec 03 '18 at 22:32

0 Answers0