Just to add some more information to what @Maniero already said, if you use numerical indices, you still use the array as a normal array.
See with index 10
for example:
let array = [];
console.log(array, array.length);
array[10] = 2;
console.log(array, array.length);
Here you see that by setting the position 10
to a value, all previous positions were defined with undefined
and at the end the array was 11
size.
But when assigning a non-numeric index already behaves as if it were a dictionary with keys and values, not appearing this information where it would appear in an array:
let array = [];
console.log(array, array.length);
array['nomeIndice'] = 2;
console.log(array, array.length);
console.log(array['nomeIndice']);
But notice that by accessing the key 'nomeIndice'
the value is there in it.
The most correct syntax for this is even the object with {}
, which makes it clear that you are dealing with braces and values, not an array where you would normally add values through push
without specifying the position:
let objeto = {};
console.log(objeto);
objeto['nomeIndice'] = 2;
console.log(objeto);