Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what situation would storing in an array different data types be useful in Javascript?

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.

like image 890
Felipe Alarcon Avatar asked Jun 10 '15 15:06

Felipe Alarcon


People also ask

Can we store different data types in array in JavaScript?

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 .

Why are arrays useful in JavaScript?

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.

Why is it appropriate to store the data in an array?

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.

Is it possible to store different types data in an array?

No, we cannot store multiple datatype in an Array, we can store similar datatype only in an Array.


1 Answers

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
};
like image 168
Konstantin Dinev Avatar answered Sep 18 '22 19:09

Konstantin Dinev