Thursday, March 30, 2017

JavaScript filter thisArg

I was attempting to write an amazing filter that would just return an array of objects where a property was true or false (and I wanted to be able to choose a value at runtime). This seemed reasonably straight forward:

function filterBySomeProp(object) {
  return object.someBoolProp === this;
}
bigArrayOfObjects.filter(filterBySomeProp, true);

Unfortunately it didn't give the expected result - turns out when passing the primitive bool as the thisArg, it gets converted to a Boolean object, and strict equality checks fail (e.g '===') as the value and type is checked. This is fixed by wrapping the primitive value when doing the check:

function filterBySomeProp(object) {
  return Boolean(object.someBoolProp) === this;

}

Happy filtering!