Javascript: returning [0] as a filter op result

While writing a filter op in javascript, I had a “res” javascript variable which I wished to return as the filter op result. So I wrote “return [res]” as my filter final instruction:

  return function(source, operator, options) {
    // some stuff here....
    let result = [];
    source((tiddler, title) => result.push(title));
    let value = result.reduce(fnCalc, initialValue);
    return [value];
  };

Most of the time, “res” was a string and that code worked fine.

Sometimes it was an integer and that code worked fine as long as it was not equal to zero.

But if I returned [0] then for the filter expression, there was no returning value at all from my filter!

To fix the bug, I converted everything as a string, by doing “return[${res}]” and returning [“0”] was working fine.

So my question is: could you explain why? I know a filter is expected to return an array of strings, but I’m still puzzling about this issue.


Jean-Pierre

PS : I’m working with tw 5.3.1

You can try this: return value + "";, which will always convert integers to strings


In JS there are several values that return “falsy” values: false, null, undefined, “”, ‘’, 0 (zero), NaN …

So if you return the string “0” it will be “truthy”.

In the TW core code we try hard to use “strict equality” eg: if (varName === "abc") for comparisons.

Sometimes it may be needed to make explicit type conversion to avoid problems like this one.

Hope that helps.
I did not have a look at the js code that is involved in filter evaluation.

Thank you @PM. This truthy stuff is what took me.

As for res + "" I instead used ${res} as I code in ES6+