1

I have this (very simple) code:

Array.prototype.test = function(x) { alert(x) }
[0].test('Hello, World!')

However, when I execute it, I get this:

TypeError: Cannot call method 'test' of undefined

What is wrong?

tckmn
  • 52,184
  • 22
  • 101
  • 145
  • (this is a *very* weird error that I spent a while debugging, so I decided to post it here for future reference to help other programmers later) – tckmn Jul 09 '13 at 18:14
  • If you prefer to omit semicolons, then it can be helpful to simply never start a line with `[` or `(`. I usually just do something like `;[0].test(...)`. –  Jul 09 '13 at 18:21
  • don't forget to always add semis after a method assignment. – dandavis Jul 09 '13 at 18:32

1 Answers1

5

I ran into this this odd error, and I finally figured out that the solution is to add semicolons:

Array.prototype.test = function(x) { alert(x) };
[0].test('Hello, World!');

Otherwise, it would be parsed like this:

Array.prototype.test = function(x) { alert(x) }[0].test('Hello, World!')

function(x) { alert(x) }[0] is undefined because function objects don't have a property called 0, so it becomes

Array.prototype.test = undefined.test('Hello, World!')

Then, it tries to call test on undefined, which it of course can't do, so it gives an error.

tckmn
  • 52,184
  • 22
  • 101
  • 145
  • 1
    Useful reference: http://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi – bfavaretto Jul 09 '13 at 18:21