declaring an array with "new Array()" vs "[]"

S

sonic

what exactly is the difference ?

I think that [] is more suitable for declarative arrays, but not
exactly sure why.

TIA
 
M

Martin Honnen

sonic said:
what exactly is the difference ?

The difference between
new Array()
and
[]
?
Both expressions create (not declare!) an empty array. [] is shorter and
was added to the language later but nowadays browsers that don't support
the [] syntax are extinct so it is pretty much your choice of preference
what you use.
 
S

sonic

thanks,

so are you saying is that there is absolutely no difference in
javascript object model between both approaches ?
 
D

Douglas Crockford

sonic said:
so are you saying is that there is absolutely no difference in
javascript object model between both approaches ?

There is a difference:

new Array(30)

is not the same is

[30]

The array literal notation is better.

http://www.JSON.org
 
V

VK

Do you mind elaborating as to why it is better ?

Both Array() and [] are equal if you create (oops... "instantiate") an
empty array. You can check the set of build-in properties/methods. they
are equal (because the same constructor is used).

They treat differently arguments (if you instantiate some array
elements right away).
Array(args) scheme is rather tricky, so [args] leaves you lesser place
for a typo.

Read more here:
<http://www.geocities.com/schools_ring/ArrayAndHash.html#Array_create>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top