1

When i execute the below code i get the below error. uncaught TypeError: object is not a function

    <html>
    <script>
    var obj_1 = {x:1, y:2}
    (function (o)
    {
        for(i in o)
        {
        console.log(i);
        }
    })(obj_1);

    </script>
    </html>

Please explain what causes this error? Thanks.

1 Answer 1

5

You're missing a semi-colon after your declaration. It thinks you're trying to call {x:1, y:2}(). Semi colons are optional and usually work, unless you have something ambiguous as you do.

That is why you should always use semi-colons;

Another thing you should always do is not create global variables as you are in your for loop

// This works
var obj_1 = {x:1, y:2};
(function (o)
{
    for(var i in o)
    {
    console.log(i);
    }
})(obj_1);

When you don't finish a line with ;, JavaScript will first try to incorporate the next line into the statement, if it can't, then it acts as if there were a ;.

// The following inserts a semi-colon because
// "var x = 2 x = 3" is not a valid statement
var x = 2
var x = 3

// The following does not insert a semi-colon because
// "var x = $().height(50).width(100);" is a valid statement
var x = $('p').
       height(50).
       width(100);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Juan, would you please explain why this error occurs in general?
@user2713706 Which part is not clear? Because you don't have a semi colon, the JavaScript engine tried to make a function call out of your () that follows the object declaration {x:1, y:2}

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.