20

I was just playing around with JavaScript and got stuck with a simple program.

I declared an array in JavaScript like

var a = [0, 1, 2];

Then as there is no fixed size for an array in JavaScript and we can add more to the array, I added another integer to array.

a[3] = 3;

And as expected If I try to access a[4] I am definitely going to get it as undefined.

Now, if I take an array

var a = [0,1,2];

And add another element

a[4] = 4;

I have intentionally not defined a[3], and this also gives me a[3] as undefined.

Here is a fiddle where this can be observed: http://jsfiddle.net/ZUrvM/

Now, if I try the same thing in Java,

int[] a = new int[4];
a[0] = 0;
a[1] = 1;

a[3] = 3;

Then I end up with

a[2] = 0;

You can see this on ideone: https://ideone.com/WKn6Rf

The reason for this in Java I found is that the four variables are defined while declaring the array and we can only assign values to the declared size of array. But in JavaScript when I declare an array of size 3 and then add 5th element why does it not consider the 4th element to be null or 0 if we have increased the array size beyond 4?

Why do I see this strange behavior in JavaScript, but not in other languages?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88

3 Answers3

17

Why is this strange behavior in JavaScript?

Because arrays are only objects. If you access a nonexisting property, you get back undefined. You simply didn't assign an element at index 3, so there is nothing.

Auto-growing the array by assigning higher indices does not change this behaviour. It will affect the .length property, yes, but the intermediate indices will stay nonexistent. This is known as a sparse array.

Why is this strange behaviour in Java / C / C++?

Because arrays are chunks of allocated memory, and when allocating an array of size 4, all its elements take their values from that memory location. To avoid indeterminate values, in some languages/occasions the fields get default-initialised, typically with 0.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    Allocating an array, in C, does not automatically initialise it with `0`. – Frames Catherine White Mar 21 '15 at 08:25
  • Arrays are objects in Java as well. However they have a fixed size and all indexes are initialized to its default. The default for a numeric type is 0. A boolean defaults to false. An object defaults to null. – Gabe Sechan Mar 21 '15 at 09:27
  • because ... in Javascript arrays are a collection of references and in Java arrays are a collection of values of the defined type (and initialized as such) – Skaperen Mar 21 '15 at 09:56
  • @Oxinabox: You're right, I've fixed that paragraph. – Bergi Mar 21 '15 at 13:07
  • @Skaperen: Even Javascript, arrays are a (indexed) collection of *values*, not of references. – Bergi Mar 21 '15 at 13:08
3

JavaScript isn't a strongly typed language.

In Java you declared an array of integers. The default value of any element in that array is 0.

In JavaScript, when you declare an array, the default value is undefined as it can hold anything, number, string, any object (including another array). All elements of a JavaScript array don't have to be the same type.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Smeegs
  • 9,151
  • 5
  • 42
  • 78
3

An array is a continuous collection of data. Say if you have a value at index 1 and index 10, the rest will be filled by undefined.

You can't create an array with empty values. 'Empty in your sense', is not undefined or null, it's empty :)

That continuous data is undefined means default assignment in JavaScript.

Say if you defined a variable,

var X;
console.log(X)    //Undefined

it's not null. null is a user explicitly specifying a way to tell there is an empty data, and undefined is the JavaScript engine way.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sarath
  • 9,030
  • 11
  • 51
  • 84
  • that's what my question is if you have value at index 1 and index 10 why the rest don't get assigned why are they not defined yet if we already have defined 10th element the there should be continuous data from 1 to 10 at least a null assigned to each one. – Naeem Shaikh Jun 04 '14 at 13:44
  • In fact, no. The rest will **not** be filled with `undefined` values. Those properties don't exist, and [even have a special display when logged](http://stackoverflow.com/questions/10683773/what-is-undefined-x-1-in-javascript). They only yield `undefined` when being accessed. – Bergi Jun 04 '14 at 13:46
  • 1
    if not assigned values are defaultly set to undefined, this is javascript's behavior. – Jai Jun 04 '14 at 13:46
  • so why is it called an array if it doesn't have continuous allocated data – Naeem Shaikh Jun 04 '14 at 13:47
  • see javascript is a loosely typed language yet very dynamic, so it has both pros and cons, so people normally gets confused with js behavior. – Jai Jun 04 '14 at 13:49
  • 1
    @NaeemShaikh27 that continuous allocated data reference is undefined – Sarath Jun 04 '14 at 13:53
  • @ sarath . that might be true but then question arise that what if i just do console.log(x) without declaring x. javascript will of course return undefined, doesn't mean x is already defined before accessing x. – Naeem Shaikh Jun 04 '14 at 13:59
  • Yes now you got the point , Try and see wht you got ? its a reference error not undefined `ReferenceError: X is not defined` , means JavaScript engine doesn't even allocate an empty(undefined) memory for X, and hence no reference point. – Sarath Jun 04 '14 at 14:01
  • @Sarath I find http://jsfiddle.net/ZUrvM/1/. It gives the array length to be 5 so it proves your statement that continuous allocated data reference is undefined. – Naeem Shaikh Jun 04 '14 at 14:05
  • 2
    Again, no: There is no continous allocated data. Lets define an array of length 5 that is *empty* (not consisting of `undefined` values): `var x = [,,,,,]; x.length == 5`. Now lets check whether the index 2 exists in this array: `"2" in x // false`. Assign a value there: `x[2] = undefined` - and it exists: `"2" in x // true`! – Bergi Jun 04 '14 at 14:09
  • @ Bergi http://jsfiddle.net/ZUrvM/3/ here it still doesn't show existing after assigning undefined to x[2] – Naeem Shaikh Jun 04 '14 at 14:16
  • http://stackoverflow.com/questions/2235622/setting-a-variable-to-undefined , there is a evil in setting values to undefined by a user , undefined should not be used be used by programmer. – Sarath Jun 04 '14 at 14:18
  • @NaeemShaikh27: That's the wrong test in the if-condition! Any falsy value (`false`, `null`, `undefined`, `NaN`, `0`, `""`) would make that test fail even if the *property* exists. I've used the [`in` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in) in my example – Bergi Jun 04 '14 at 19:29