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];
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
.
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.
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.