4

Please refer - https://jsfiddle.net/53ranmn5/1

Array.prototype.method1 = function() {
console.log("method1 called");
}
[1,2,3,4].method1();

I get the following error,

TypeError: Cannot read property 'method1' of undefined

Why so? How can I fix this?

16
  • 1
    jsfiddle.net/53ranmn5/1 Commented Apr 23, 2015 at 14:42
  • 1
    Your code works just fine, although console.log([1,2,3,4].method1()); prints out undefined (in your fiddle) since method1 does not return any string itself. Commented Apr 23, 2015 at 14:43
  • 1
    You've included what you tried, but not what you expect or what went wrong. Commented Apr 23, 2015 at 14:43
  • 2
    @gopalrao My bad. Your code has a real problem. You should use ; after the function definition. JavaScript treats function () {..}[1, 2, 3,4] as a Single expression. And since it returns undefined, you are getting the error. Commented Apr 23, 2015 at 14:46
  • 1
    @ScottKaye That is why I apologized and voted to reopen. Commented Apr 23, 2015 at 14:50

2 Answers 2

10

You're missing a semicolon:

Array.prototype.method1 = function() {
    console.log("method1 called");
}; // <--- Hi there!
[1,2,3,4].method1();

What?

Semicolons are optional in javascript, so the code you wrote is equivalent to:

Array.prototype.method1 = function() { ... }[1,2,3,4].method1();
// after evaluating the comma operator:
Array.prototype.method1 = function() { ... }[4].method1();
// naturally, functions don't have a fourth index
undefined.method1();
// Error :(

Be careful with your semicolons!

Some reading material:

Sign up to request clarification or add additional context in comments.

Comments

0

Works fine for me, just added one character:

Array.prototype.method1 = function() {
    console.log("method1 has been called");
};
[1,2,3,4].method1();

3 Comments

Please explain why the "one character" is necessary here.
Your code is correct, when run under console. This bug must belong to jsfiddle alone. Compare it with this: stackoverflow.com/questions/948358/…
@Beri When run inside a console, statement by statement, the bug isn't there because the array isn't there to confuse the js engine into thinking it's a property access.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.