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.
-
1"Should be" is not the same as must be.deceze– deceze ♦2017年06月28日 07:31:18 +00:00Commented Jun 28, 2017 at 7:31
-
3Where did you take this definition of "Array" from? (E.g.: exact source of the quote)UnholySheep– UnholySheep2017年06月28日 07:31:20 +00:00Commented Jun 28, 2017 at 7:31
-
1He took the definition from Tutorials point's Data Structures and Algorithms - Arrays as it seems.Kakashi Hatake– Kakashi Hatake2017年06月28日 07:34:11 +00:00Commented Jun 28, 2017 at 7:34
-
2Don't believe everything you read on the internet.shmosel– shmosel2017年06月28日 07:34:47 +00:00Commented Jun 28, 2017 at 7:34
-
@UnholySheep - Here's the link from where I took the definition of Array - tutorialspoint.com/data_structures_algorithms/…Jagan N– Jagan N2017年06月28日 07:35:32 +00:00Commented Jun 28, 2017 at 7:35
2 Answers 2
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.
1 Comment
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).