The meaning of “'x' is not a function or its return value is not iterable” error

前端 未结 1 708
天涯浪人
天涯浪人 2021-01-18 07:27

I accidentally witnessed that this causes an error in V8 (Chrome, Node.js, etc):

for (let val of Symbol()) { /*...*/ }

TypeError

相关标签:
1条回答
  • 2021-01-18 08:31

    Yes, there is meaning to both parts of the error message. In the case you have at hand, the return value of Symbol() is not iterable, so that's the second option. As an example for the first option, just take something that's not a function:

    let NotAFunction = {};  // Or any other object.
    for (let val of NotAFunction()) {}
    

    gives: Uncaught TypeError: NotAFunction is not a function or its return value is not iterable. In this case, clearly, NotAFunction is not a function ;-)

    I don't know why there aren't two separate error messages for "it's not a function at all" and "it was a function and it's been called, but its return type wasn't iterable". Presumably something in the internal logic to implement for..of loops made it prohibitively complicated to have finer-grained error reporting -- so the combined error message simply mentions two possible reasons why the loop didn't work.

    0 讨论(0)
提交回复
热议问题