Search code examples
javascriptslickgrid

What's the purpose of str.indexOf(var && var)?


I've found in a library that I'm using this piece of code:

item[column.field].indexOf(columnFilters[columnId] && columnFilters[columnId]) === -1)

and I'm wondering what's the purpose of passing the same value twice to indexOf. Or is it just a mistake and I can correct it.

Library: https://github.com/6pac/SlickGrid/blob/master/examples/example16-row-detail.html (live http://6pac.github.io/SlickGrid/examples/example16-row-detail.html)


Solution

  • Frankly it almost certainly doesn't make any sense there. columnFilters[columnId] && columnFilters[columnId] is effectively the same as columnFilters[columnId] except that columnFilters[columnId] may get evaluated twice (if it's falsy). Unless columnFilters has an accessor property with the name in columnId that has a side effect, && is completely pointless there. (If it does, it'll cause its side effect twice if the result is falsy.)

    && evaluates its left-hand operand and, if it's falsy, takes that value as its result; if the left-hand operand evaluates truthy, && evaluates the right-hand operand and takes that value as its result. So you can see why it's pointless in this case unless it's being used for side-effects from accessors, in which case it's just...a bad idea. :-)