Reputation: 2065
I am a beginner to Javascript and learning the concepts. I came across the below code snippet as part of my learning process.
<script>
var data=[];
data.push("100");
data.push(100);
var object=[];
object.string="100";
object.number=100;
data.push(object);
console.log(data);
</script>
The above code snippet defines an Array and pushes a String, Number and an Object into it. I think this violates the definition of an Array which reads as follows:
Array is a container which can hold a fix number of items and these items should be of the same type.
I would like to know if Array is the right term to be used in this case as the elements are not of the same type.
Upvotes: 1
Views: 956
Reputation: 522165
The "should be" here most likely refers to the fact that logically homogeneous collections are easier to deal with than heterogeneous collections. If you have an array of numbers, you can do aggregate operations such as summing them easily; if you have a mixed array of stuff, you need to pick it apart one by one and can't easily do anything with it. That's often a sign of a badly structured program.
There's no technical reason why collections must be homogeneous, especially in a dynamically typed language like Javascript (more so in statically typed languages).
Upvotes: 0
Reputation: 121998
You understand/read them incorrect (in case of javascript).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed.
And yes, this definition is purely for Javascript. For ex: Java arrays are strictly type based.
Upvotes: 2