1

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"); 
4
  • Because that is the convention as every programming language uses brackets to access an assay? Commented Jan 1, 2018 at 5:58
  • 1
    You wouldn't be able to use tweets() because that means you are calling the tweets function, which doesn't exist. "tweets" is not a function it is an array. Commented Jan 1, 2018 at 6:00
  • Because tweets isn't a function, its an array and you access elements in an array using square brackets only. Commented Jan 1, 2018 at 6:00
  • 2
    Round brackets after an expression are always for function calls, and square brackets after an expression are always for property access. Array values are properties. Commented Jan 1, 2018 at 6:01

3 Answers 3

2

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.

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

Comments

1

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.

Comments

0

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:

  • I don't know the specification name of the above operators, will need expert explanation on them.
  • A function is an object so you can use both operators on it

e.g.

var func = function() { return 'hello'; };

func.world = 'earth'
console.log(func());
console.log(func['world'])
console.log(func.world)

Comments

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.