Reputation: 147
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.
Upvotes: 1
Views: 45
Reputation: 92274
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);
Upvotes: 5