0

I'm trying to use destructuring to extract the map function from an array. The method seems to be destructured correctly. But I get the following error when I try to use it:

Uncaught TypeError: Array.prototype.map called on null or undefined

Shouldnt it be able to access the array using its scope?

const array = [1,2,3,4]
const {map} = array
console.log({map})
map(x => x*x) // Uncaught TypeError: Array.prototype.map called on null or undefined
Rashomon
  • 5,962
  • 4
  • 29
  • 67
  • 3
    The destructuring is fine. The problem is that when you call `map` like that, `this` within the call is either `undefined` (in strict mode -- which you seem to be using [good!]) or the global object (in loose mode), neither of which is your array. :-) You'd have to do `map.call(array, x => x * x)` to set `this` correctly. Or use `bind` (in which case you probably wouldn't use destructuring, `const map = array.map.bind(array);`) Details in the linked question. – T.J. Crowder May 01 '20 at 16:48
  • Why dont you simply use array.map(x => x*x) ? – David May 01 '20 at 16:48
  • @David - Presumably there's more to the actual problem the OP is solving, but it wasn't relevant to the question. – T.J. Crowder May 01 '20 at 16:49
  • @T.J.Crowder All builtin methods are implicitly strict, so `map` never defaults to the global object. – Bergi May 01 '20 at 16:56
  • @Bergi - Do you know, I'm not sure I ever ran across that before. A quick experiment sez: seems to be true. Thanks! Do you know where that is in the spec? I kicked around a bit but didn't find it in ~5 minute so searching. Seems like the kind of thing they'd want to list [here](https://tc39.es/ecma262/#sec-strict-mode-code). (You know how I am, I like to see the spec text...) :-) – T.J. Crowder May 01 '20 at 18:35
  • @T.J.Crowder https://stackoverflow.com/a/60288194/1048572 says it's in the "built-in function objects" section – Bergi May 01 '20 at 18:49
  • @Bergi - Yup, [here](https://tc39.es/ecma262/#sec-built-in-function-objects): *"Built-in functions that are ECMAScript function objects must be strict functions."* – T.J. Crowder May 01 '20 at 18:56

0 Answers0