Reputation: 11
In class, teacher couldn't explain why tweets(i) failed and tweets[i] works:
var tweets=["hi","who","when","where","bye"];
alert("start");
for (var i=0; i < tweets.length; i++) {
alert(tweets[i]);
}
alert("finish");
Upvotes: 1
Views: 90
Reputation: 895
The ()
is a method invocation operator and the [x] is an member access operator. As array is not a function (e.g. typeof array !== 'function'
), so you can only use member access operator on the array.
Note:
e.g.
var func = function() { return 'hello'; };
func.world = 'earth'
console.log(func());
console.log(func['world'])
console.log(func.world)
Upvotes: 0
Reputation: 3618
Brackets are used for functions, so array()
would be a function called array
. Square brackets are used for arrays, so array[]
would be an array. array[0]
is the first entry in an array, array(1)
would send 1
as an argument to a function called array
.
And stop going to classes where the teacher can't explain something this simple. They clearly aren't a programmer.
Upvotes: 2
Reputation: 104
The reason tweets(i) fails in this code snippet is because, when you say tweets(i)
, javascript looks at it and says "oh, the code wants me to go find a function named tweets and execute it with a parameter named i."
When javascript sees tweets[i]
, it says "oh, this isn't a function. The code wants me to find the number-i place in an array and give it back the value stored there.
In short, The reason tweets(i)
doesn't work is because you're telling it to alert a function that you haven't defined.
Upvotes: 1