During a recent javascript project, I attempted something like the following code snippet. To my surprise, it did not work and instead produced an error message.
const test = [1, 2, 3, 4];
const something = [1, 2, 3, 4, ,5, 6, 7, 8].filter(test.includes);
console.log(something);
TypeError: Cannot convert undefined or null to object
at includes (<anonymous>)
at Array.filter (<anonymous>)
at evalmachine.<anonymous>:3:45
at Script.runInContext (vm.js:74:29)
at Object.runInContext (vm.js:182:6)
at evaluate (/run_dir/repl.js:133:14)
at ReadStream.<anonymous> (/run_dir/repl.js:116:5)
at ReadStream.emit (events.js:180:13)
at addChunk (_stream_readable.js:274:12)
at readableAddChunk (_stream_readable.js:261:11)
I wonder if this is a bug in javascript or if I am simply misunderstanding something. The two working alternatives are shown below:
const test = [1, 2, 3, 4];
const something = [1, 2, 3, 4, ,5, 6, 7, 8].filter(item => test.includes(item));
console.log(something);
And:
const test = [1, 2, 3, 4];
const someFunc = theThing => test.includes(theThing);
const something = [1, 2, 3, 4, ,5, 6, 7, 8].filter(someFunc);
console.log(something);
As I strive for a more functional programming style and aim for point-free patterns where possible, encountering such inconsistencies is slightly frustrating.
Edit: This is not repeated content. My question is not about This
, but rather how it interacts with the includes function specifically.