1

If I want to make an array that is say of length 3 using bracket notation, should I just write: var foo = [,,];

I was more used to writing: var foo = new Array(3);

I noticed that if I removed one , that my code still worked which is surprising because I am accessing all 3 elements after assigning them. How is it that it would still work?

3
  • Just to note: if you need an Array with specific length n, you can use Array(n).join().split(','). So, if you need an Array containing 100 empty elements: Array(100).join().split(','). Commented Aug 24, 2013 at 9:09
  • Why not just write new Array(100)? Commented Aug 24, 2013 at 9:13
  • should've mentioned it. Using Array(100) you can't use methods like map. E.g. Array(100).join().split(',').map(function(){return 1;}) returns an Array containing 100 elements with value 1, Array(10).map(function(){return 1;}) an Array containing 100 elements with value undefined Commented Aug 24, 2013 at 9:32

1 Answer 1

2

if u do

a = []
a[3] = 100

the indices 0,1,2 will be filled in with undefined for u. u do not have to set a specific array length before using certain indices. array will grow as u use it.

all these are the same:

a = [,,,]

b = []
b.length = 3

c = new Array(3)

d = []
d[2] = undefined
Sign up to request clarification or add additional context in comments.

3 Comments

I did not realize it just grew. Is there any advantage to specifying the length with commas if I know what the final length should be?
@asimes [,,,] makes an array of 3 elements. i kno its weird. i dont think theres an advantage, maybe slightly faster if it can do allocation all at once instead of one index at a time. but thats a micro optimization.
That is weird... I guess a = [] makes an array of length 0

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.