I have been learning some javascript recently and found out that you can store different data types in an array like this:
var myArray = [12, 23.5, "hello", true];
I have some Java background and this is not possible in Java as you would have to declare the data type otherwise you would get an error (int myArray = blah blah blah
)
So my question is, in what situations would you use this instead of an object for example. Examples would be great. Thanks.
JavaScript arrays can indeed contain any and all types of data. An array may contain other objects (including other arrays) as well as any number of primitive values like strings, null , and undefined .
In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable.
Arrays are used when there is a need to use many variables of the same type. It can be defined as a sequence of objects which are of the same data type. It is used to store a collection of data, and it is more useful to think of an array as a collection of variables of the same type.
No, we cannot store multiple datatype in an Array, we can store similar datatype only in an Array.
This is the case in any language that is not strongly typed. Your array members can be of different primitive and they also can be objects. In most cases you wouldn't want to use this because there is no clear structure to your array. You would rather have something like:
var data = {
prop: 12,
otherProp: 24.5,
stringProp: "hello",
boolProp: true
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With