5

In JavaScript, if you set an array to be of size 5 ( var foo = new Array(5); ), is this just an initial size? Can you expand the number of elements after it is created. Is it possible to do something like this as well - arr = new Array() and then just assign elements one by one? Thanks in advance :-)

rubixibuc
  • 7,111
  • 18
  • 59
  • 98

6 Answers6

5

Yes it is just an initial size, and it is not required. If you don't use a single number, you can immediately populate.

It is also more common to use the simpler [] syntax.

var arr = ['something', 34, 'hello'];

You can set (or replace) a specific index by using brackets:

arr[0] = "I'm here replacing whatever your first item was";

You can add to the end by using push:

arr.push('add me');

There may be faster performance in some browsers if you do it like this instead:

arr[arr.length] = 'add me';

You can add something at any index.

You can remove an item completely using splice:

arr.splice(0, 1); // remove first item in the array (start at index 0, with 1 being removed)
Brett Zamir
  • 14,034
  • 6
  • 54
  • 77
  • Is the [] like an anonymous array? – rubixibuc Jun 03 '11 at 20:20
  • @rubixibuc: No, it is an array literal. – Felix Kling Jun 03 '11 at 20:22
  • What is the difference between a array literal and a anonymous array? (sry if this is a silly question :-/) – rubixibuc Jun 03 '11 at 20:25
  • @rubixibuc i think its when you create an array without a reference. – Matt Jun 03 '11 at 20:27
  • All arrays are anonymous. For aeons in JS versions, it has effectively been the same as `new Array()` or `Array()` (except for the obscure difference where if you confusingly put a trailing comma inside, it won't give an error with the literal). – Brett Zamir Jun 03 '11 at 20:28
  • Literal just means you are initializing it as is. It is not appearing like a function constructing an array, it IS itself the syntax for an array. – Brett Zamir Jun 03 '11 at 20:30
  • @rubixibuc: You might confuse this with *anonymous functions*. I have never heard the term *anonymous array*. – Felix Kling Jun 03 '11 at 20:31
  • It's not helpful to speak of "anonymous arrays"--You can refer to "anonymous functions" which are used either for namespacing, something more advanced called closures, or as data: `horseWithNoName(function () {alert("I've been through the desert";});` The function passed in here has no name whereas `function IHaveAName () {}` is not anonymous. – Brett Zamir Jun 03 '11 at 20:33
  • See: http://stackoverflow.com/questions/931872/whats-the-difference-between-array-and-while-declaring-a-javascript-arr for an answer on the difference. The answer by @coderjoe is excellent and explains this concept thoroughly – Chris Baker Jun 03 '11 at 20:34
  • Good point Chris: though as stated in the comments, writing your own Array then expecting it to be the native Array() would be pretty strange. As to performance, in FF4, on creating 100,000 empty or multiple-itemed arrays in a loop, the constructor is a few milliseconds slower, so not exactly a big problem. – Brett Zamir Jun 03 '11 at 20:50
5

When you give a new array an explicit size in javascript (using new Array(5)), you populate each index with value of undefined. It is generally considered better practice to instantiate using the array literal [] expression:

var arr = [];

Then, you can push new elements using push()

var arr = [];
arr.push('first value'):
arr.push('second value'):

Check out the MDC Array documentation for more info: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array

Chris Baker
  • 49,926
  • 12
  • 96
  • 115
  • 1
    Actually when writing `new Array(5)`, each index is still `undefined` (which is different than `null`). It is more like doing `var arr = []; arr.length = 5;`. – Felix Kling Jun 03 '11 at 20:20
2

Theres a few ways to declare and put values in an array.

First like what you want to do,

var myarr = new Array();
myarr[0] = 'element1';
myarr[1] = 'element2';
myarr[2] = 'element3';

Second way is to define them

var myarr =new Array("element1","element2","element3");

and third is similar to the second

var myarr =["element1","element2","element3"];

You can also check out https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array for a little more information about using the arrays as well. You could use push and pop if you wanted to as well.

If you use jquery or mootools they also have built-in functions to perform on arrays, http://api.jquery.com/jQuery.each/ for instance.

Matt
  • 7,049
  • 7
  • 50
  • 77
1

Have a look at http://www.w3schools.com/js/js_obj_array.asp

var myCars=new Array(); // regular array (add an optional integer
myCars[0]="Saab";       // argument to control array's size)
myCars[1]="Volvo";
myCars[2]="BMW";
Dnns
  • 2,614
  • 3
  • 18
  • 16
1

Check the documentation for Array, but the simple answer to your question is yes.

var arr5 = new Array(1, 2, 3, 4, 5); // an array with initial 5 elements
var arr = new Array(); // an array without initial

You can also use array literals:

var arr5 = [1, 2, 3, 4, 5];
var arr = [];
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
0

Arrays are dynamic in JavaScript. You don't have to initialize them with a certain length. In fact you should use the literal notation [] because of the Array constructor's ambiguity:

If you pass only one parameter to Array, it will set the array length to this parameter. If you pass more than one parameter, these elements are added to the array.

How is the size of the array determined?

The size of an array is the highest index + 1. This can be quite confusing. Consider this:

var arr = [];
arr[41] = 'The answer?';
console.log(arr); // [undefined, undefined, ..., 'The answer?']
console.log(arr.length) // 42

You can even set the length yourself by assigning a number to .length:

arr.length = 99;

If you now add a new element using arr.push(), it will get the index 100 and the length will increase. Whenever you add an element to the array via an index, it is tested whether arr.length is smaller than the index and updated accordingly. But it does not get smaller.

So in fact what var arr = new Array(5) is doing is setting the length of the array to 5. Nothing else.


For more information about creating and populating arrays, I suggest to read about it in the MDC JavaScript Guide.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143