0

what is wrong with this below code ? why it is printing size of array as zero?

function test() {
  var arr = [];
  for(var i = 0; i < 10; i++)
  {
    console.log('i ->' + i);
    arr.push[i];
  }
  console.log('\n' + 'array length :' + arr.length);
}

--

Output:

i ->0
i ->1
i ->2
i ->3
i ->4
i ->5
i ->6
i ->7
i ->8
i ->9

array length :0

--

it is printing as zero(0)

1
  • 2
    Not sure why you're using a subscripting operator there []... try arr.push(i);. Commented Oct 29, 2013 at 17:28

2 Answers 2

11

push is a function.

You need to write arr.push(i) and not arr.push[i]. What you're doing in the latter is referring to arr.push as if it were an array, and then trying to access its ith subscript (or assuming that push is an object and trying to access a property that has the same value of i); it's effectively the same as writing a single line statement like so:

someArray[i];

Which doesn't really do anything.

Note: I have been bitten by this silly bug many times as well when I type too fast. ;)

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

Comments

4

Because .push[i] should be .push(i).

The reason you didn't get an error is that functions are objects in JavaScript, so you can legally get and set properties on functions.

What you were doing was fetching the the i property from the Array.prototype.push method (which will be undefiend).

console.log(arr.push[i]); // undefined

Probably worth noting that jsHint would catch this for you.

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.