0

It seems like I'm missing something.

For example:

const validNames = ['John'];
const includesFilter = validNames.includes;

// I would expect this call to evaluate to true.
includesFilter('John'); // throws error: "Uncaught TypeError: Cannot convert undefined or null to object"

// Of course, the function can be wrapped.
const includesFilterWrapped = (name) => validNames.includes(name);
// this call evaluates to true
includesFilterWrapped('John');

Also, when applied to a filter:

const names = ['John', 'Mary', 'Sally'];
const validNames = ['John'];

// I would expect this call to evaluate to an array containing only 'John'
names.filter(validNames.includes); // throws error: Uncaught TypeError: Cannot convert undefined or null to object

// This call runs, but it would be slick to use the shorthand if possible. Or at least, I would hope to learn why it won't work here.
names.filter((name) => validNames.includes(name);
skylerfenn
  • 354
  • 3
  • 10
  • 2
    `Array.prototype.includes`, while being a native method, is defined in such a way that it uses `this` as the supposed array that you want to check your value against. Calling `includesFilter` calls the method with `this` as `undefined` in strict mode or `globalThis` in sloppy mode; `validNames` is lost. `const includesFilter = validNames.includes.bind(validNames)` or `includesFilter.call(validNames, "John");` explicitly passes a value for `this` and should work, but that’s not shorter than using `validNames.includes(`…`);` directly. See [How does the `this` keyword work?](/q/3127429/4642212). – Sebastian Simon Nov 01 '22 at 17:31

0 Answers0