Wenfang Du
Wenfang Du

Reputation: 11317

Optional Chaining - Function.prototype.apply was called on undefined, which is an undefined and not a function

Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found.

Note: The code is using spread syntax, not rest parameters.

const fn1 = undefined
const args = []
const fn2 = () => {}
const fn3 = () => {}

console.log(fn1?.(...args, fn2, fn3))

Error:

console.log(fn1?.(...args, fn2, fn3))
                                ^
TypeError: Function.prototype.apply was called on undefined, which is an undefined and not a function

Upvotes: 16

Views: 3969

Answers (2)

Wenfang Du
Wenfang Du

Reputation: 11317

It turns out to be a V8 bug, I've submitted it there, hopefully, it'll be fixed soon.

Update: it has been fixed.

Upvotes: 10

bob
bob

Reputation: 7985

There are a couple rules to follow with ...rest arguments.

One of those rules is that the ...rest argument can only be the last argument.

foo(...one, ...wrong, ...wrong)
foo(...wrong, bad, bad)
foo(ok, ok, ...correct)

See:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

Upvotes: -4

Related Questions