1

I'm trying to add an any method to Array.

Array.prototype.any = (pred) => {
  for(const item of this) {
    if (pred(item)) {
      return true
    }
  }
  return false
}

console.log([1, 2, 3].any(num => num === 3))

...but I'm getting the error:

Uncaught TypeError: undefined is not a function
    at Array.any (array.js:4)
    at array.js:13

I was expecting true to be printed to to the console. What did I do wrong?

Michael Dorst
  • 8,210
  • 11
  • 44
  • 71
  • `TypeError: this is not iterable` is the error you’re actually getting. – Sebastian Simon Nov 03 '19 at 00:51
  • It looks like because I'm using `this`, I needed to use traditional `function` syntax rather than arrow function (`() => {}`) syntax. – Michael Dorst Nov 03 '19 at 00:52
  • @SebastianSimon actually no, after replacing the arrow function with a regular function I don't get any error. Can you elaborate? – Michael Dorst Nov 03 '19 at 00:54
  • Yes, I wrote a comment to that effect @charlietfl – Michael Dorst Nov 03 '19 at 01:13
  • 2
    do you know [Array#some()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)? – Thomas Nov 03 '19 at 01:15
  • @MichaelDorst _“after replacing the arrow function with a regular function I don't get any error”_ — Exactly. Read the linked question again. It’s all explained there. – Sebastian Simon Nov 03 '19 at 03:16
  • @SebastianSimon yes, obviously, but the error I _actually got_ was the one that I posted, so why did you tell me I was "actually getting" a different error? – Michael Dorst Nov 04 '19 at 03:04
  • @MichaelDorst There’s no way to reproduce the error you originally posted. The only other reproducible error was the one related to `this`. – Sebastian Simon Nov 04 '19 at 03:08
  • @SebastianSimon copy that code into a file named `array.js` and call `node array.js` and you will see the error I posted. – Michael Dorst Nov 04 '19 at 03:25
  • 1
    @MichaelDorst Wow! That’s Chrome/V8’s way of telling you that `window` is not iterable. It actually _is_ the same error, but the V8 error message is near useless. The error is reproducible with `for(const x of window);` (or `this` instead of `window` outside strict mode). You’ll find that `window` is not iterable (sensible error message in Firefox). What JS is trying to do is call the [`Symbol.iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator) method on `window`. The method resolves to `undefined`, hence Node says it’s not a function. – Sebastian Simon Nov 04 '19 at 06:41

0 Answers0