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
?