473,659 Members | 2,681 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

new Array() vs []

Hello, one is pretending it is /better/ to use new Array() and *never*
use the literal notation [], is he wrong or right ? If he is wrong, as i
suspect he is, how can i explain him, with simple terms :) he is wrong ?

http://javascript.crockford.com/code.html
Here in "Bonus Suggestions" it is write :

"Use {} instead of new Object(). Use [] instead of new Array()."

I've seen it write in a lot of ressources, but never with any concrete
explanation, so why ?

Thanks.

--
laurent
Sep 5 '06 #1
11 15907
Hi Laurent.

Laurent vilday wrote:
Hello, one is pretending it is /better/ to use new Array() and *never*
use the literal notation [], is he wrong or right ? If he is wrong, as i
suspect he is, how can i explain him, with simple terms :) he is wrong ?
Better in what way?

ECMA-262 says (11.1.4):

The production ArrayLiteral: [ Elision(opt) ] is evaluated as follows:

1. Create a new array as if by the expression new Array().
2. Evaluate Elision; if not present, use the numeric value zero.
3. Call the [[Put]] method of Result(1) with arguments "length" and
Result(2).
4. Return Result(1).

And from (15.4.2.1) you can see that new Array() would set "length" to 0
anyway. So they are just the same in terms of behaviour.

[] is shorter to type, and would be quicker to parse (assuming a
reasonable implementation) . There's no reason not to use it.

--
Cameron McCormack, http://mcc.id.au/
xmpp:he****@jab ber.org â–ª ICQ 26955922 â–ª MSN ca*@mcc.id.au
Sep 5 '06 #2
Cameron McCormack wrote:
[] is shorter to type, and would be quicker to parse (assuming a
reasonable implementation) . There's no reason not to use it.
Ancient browsers didn't support it.
I don't even remember which versions of Netscape - 3.0, perhaps? Or even
2.x?
Not using [] and {} may be a recommendation from someone who came to the
conclusion long ago an just hasn't changed it in modern times.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Sep 5 '06 #3
Matt Kruse wrote:
Cameron McCormack wrote:
[] is shorter to type, and would be quicker to parse (assuming a
reasonable implementation) . There's no reason not to use it.

Ancient browsers didn't support it.
I don't even remember which versions of Netscape - 3.0, perhaps? Or even
2.x?
Not using [] and {} may be a recommendation from someone who came to the
conclusion long ago an just hasn't changed it in modern times.
<URL: http://jslint.com >

INPUT
var x = new Array();

OUTPUT
Problem at line 1 character 13: Use the array literal notation [].

Sep 5 '06 #4
VK

pe**********@gm ail.com wrote:
INPUT
var x = new Array();

OUTPUT
Problem at line 1 character 13: Use the array literal notation [].
JSLint is a great tool with a lot of thoughts put into it, but it has
some highly specific ideas of the proper programming and syntax, so use
with caution :-)

new Array(length) can be used to instantiate an array of a given
initial length without populating it. Unless you have such intention,
squared brackets way could be used.

Yet this issue has relevance to "cool looking vs. lame looking" issue
rather then to the "good programming vs. bad programming" one :-)

Sep 6 '06 #5
JRS: In article <11************ *********@m73g2 000cwd.googlegr oups.com>,
dated Tue, 5 Sep 2006 23:18:12 remote, seen in
news:comp.lang. javascript, VK <sc**********@y ahoo.composted :
>new Array(length) can be used to instantiate an array of a given
initial length without populating it. Unless you have such intention,
squared brackets way could be used.

Indeed. But when is it useful to do so?

ISTR there's a related discussion, involving speed, in news:fr.c.l.j -
perhaps a true francophone might report any conclusions?

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/&c., FAQqy topics & links;
<URL:http://www.merlyn.demo n.co.uk/clpb-faq.txt RAH Prins : c.l.p.b mFAQ;
<URL:ftp://garbo.uwasa.fi/pc/link/tsfaqp.zipTimo Salmi's Turbo Pascal FAQ.
Sep 6 '06 #6
VK
new Array(length) can be used to instantiate an array of a given
initial length without populating it. Unless you have such intention,
squared brackets way could be used.

Indeed. But when is it useful to do so?
This is the question of a kind "what blue paint can be used for?" You
know for sure that it can be used for many things, but try to give a
sample right away :-)

It can be an array where you do not want to exceed certain length or
where you want to take extra steps when the length exceeds certain
limits.

Say (from my most recent cases) it can be a license limitation for no
more than 10 simultaneous requests to the server. It can be say 1000
records array and then you need to alert user about something (or save,
or refuse to add etc.)
Of course - as almost everything in JavaScript - it can be made in
different ways:

a)
var arr = new Array(1000);
....
if (i arr.length) {
// do something
}
....

b)
var arr = [];
var uBound = 1000;
....
if (i uBound) {
// do something
}
....

c)
var arr = [];
arr.uBound = 1000;
....
if (i arr.uBound) {
// do something
}
....

d) and so on.

But sometimes and rather often the simpliest way is the best one ;-)

ISTR there's a related discussion, involving speed, in news:fr.c.l.j -
perhaps a true francophone might report any conclusions?
JavaScript doesn't allocate/reallocate memory for undefined array
members. So there is no difference between new Array() and [] in
productivity or memory usage. There is nothing to discuss here neither
in French, nor in English - though I read the suggested thread.

Sep 7 '06 #7
ASM
VK a écrit :
>>new Array(length)
[...]
>ISTR there's a related discussion, involving speed, in news:fr.c.l.j -
perhaps a true francophone might report any conclusions?

JavaScript doesn't allocate/reallocate memory for undefined array
members. So there is no difference between new Array() and [] in
productivity or memory usage. There is nothing to discuss here neither
in French, nor in English - though I read the suggested thread.
But probably Firefox doesn't do the job as other browsers ... ?
Answering diffently when you loop a [...] using method for(i in t)

t = new Array();
t[0] = "A";
t[3] = "B";

= IE 5.2 Mac = Safari 1.3.2 = Opera 9 = iCab 3 = Fx 1.5.0.6 =
for(i=0; i<t.length; i++) ==A undefined undefined B
for( i in t ) ==A B
t = ['A',,,'B'];

= IE 5.2 Mac = Safari 1.3.2 = Opera 9 = iCab 3 =
for(i=0; i<t.length; i++) ==A undefined undefined B
for( i in t ) ==A B

= Fx 1.5.0.6 =
for(i=0; i<t.length; i++) ==A undefined undefined B
for( i in t ) ==A undefined undefined B

<http://groups.google.c om/group/fr.comp.lang.ja vascript/msg/3aa5c83edea38f5 0?rnum=1>

--
Stephane Moriaux et son [moins] vieux Mac
Sep 7 '06 #8
ASM wrote:
t = ['A',,,'B'];

= IE 5.2 Mac = Safari 1.3.2 = Opera 9 = iCab 3 =
for(i=0; i<t.length; i++) ==A undefined undefined B
for( i in t ) ==A B

= Fx 1.5.0.6 =
for(i=0; i<t.length; i++) ==A undefined undefined B
for( i in t ) ==A undefined undefined B
Firefox's behaviour is incorrect here (according to ECMA-262 11.1.4.)

--
Cameron McCormack, http://mcc.id.au/
xmpp:he****@jab ber.org â–ª ICQ 26955922 â–ª MSN ca*@mcc.id.au
Sep 8 '06 #9
I never notice this, thank you very much.
Cameron McCormack wrote:
ASM wrote:
t = ['A',,,'B'];

= IE 5.2 Mac = Safari 1.3.2 = Opera 9 = iCab 3 =
for(i=0; i<t.length; i++) ==A undefined undefined B
for( i in t ) ==A B

= Fx 1.5.0.6 =
for(i=0; i<t.length; i++) ==A undefined undefined B
for( i in t ) ==A undefined undefined B

Firefox's behaviour is incorrect here (according to ECMA-262 11.1.4.)

--
Cameron McCormack, http://mcc.id.au/
xmpp:he****@jab ber.org â–ª ICQ 26955922 â–ª MSN ca*@mcc.id.au
Sep 8 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2779
by: Brian | last post by:
I'm diddlying with a script, and found some behavior I don't understand. Take this snippet: for ($i = 0; $i <= count($m); $i++) { array_shift($m); reset($m); }
2
575
by: Stormkid | last post by:
Hi Group I'm trying to figure out a way that I can take two (two dimensional) arrays and avShed and shed, and subtract the matching elements in shed from avShed I've pasted the arrays blow from a print_r cmd any suggestions would be great. Thanks much Todd //avShed array Array ( => Array ( => 1 => 08:00 ) => Array ( => 1 => 08:05 ) => Array ( => 1 => 08:10 ) => Array ( => 1 => 08:15 ) => Array ( => 1 => 08:20 ) => Array...
15
5178
by: lawrence | last post by:
I wanted to test xml_parse_into_struct() so I took the example off of www.php.net and put this code up on a site: <?php $simple = <<<END <item>
8
3474
by: vcardillo | last post by:
Hello all, Okay, I am having some troubles. What I am doing here is dealing with an employee hierarchy that is stored in an array. It looks like this: $employees = array( "user_id" => array( "name", "title", "reports to user id", "start date in the format: mm/dd/yyyy" ) ); How can I display this hierarchy in simple nested <li> tags in the most
12
55548
by: Sam Collett | last post by:
How do I remove an item with a specified value from an array? i.e. array values 1,2,2,5,7,12,15,21 remove 2 from array would return 1,5,7,12,15,21 (12 and 21 are NOT removed, duplicates are also removed) So far I have (val is value, ar is array, returns new array):
8
10218
by: Mike S. Nowostawsky | last post by:
I tried using the "toUpperCase()" property to change the value of an array entity to uppercase BUT it tells me that the property is invalid. It seems that an array is not considered an object when it is assigned a text literal?? HOW can I change the array value to upper case then? What other method exists for arrays? Ex: var GridArrayName1 = new Array(); GridArrayName1 = new Array ('test-value'); GridArrayName1 = GridArrayName1...
58
10121
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of code... TCHAR myArray; DoStuff(myArray);
104
16929
by: Leszek | last post by:
Hi. Is it possible in javascript to operate on an array without knowing how mamy elements it has? What i want to do is sending an array to a script, and this script should add all values from that array Could you show me a little example how to do this? Thanks.
7
3191
by: Jim Carlock | last post by:
Looking for suggestions on how to handle bad words that might get passed in through $_GET variables. My first thoughts included using str_replace() to strip out such content, but then one ends up looking for characters that wrap around the stripped characters and it ends up as a recursive ordeal that fails to identify a poorly constructed $_GET variable (when someone hand-types the item into the line and makes a simple typing error).
17
7239
by: =?Utf-8?B?U2hhcm9u?= | last post by:
Hi Gurus, I need to transfer a jagged array of byte by reference to unmanaged function, The unmanaged code should changed the values of the array, and when the unmanaged function returns I need to show the array data to the end user. Can I do that? How?
0
8339
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8535
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6181
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5650
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4338
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2757
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1982
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1739
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.