Saturday 1 September 2018

JavaScript: Arrays are heterogeneous

Arrays in JavaScript are heterogeneous. You can store any kind of data in the array.

var arr = [2, "Hello", 123.5, true, person];
As you see, I can able to store different kinds of data like number, string, boolean in the same array.

array.html

<!DOCTYPE html>

<html>

<head>
    <title>Array</title>
</head>

<body>
    <script type="text/javascript">
        var person = {
            firstName: "Hari krishna",
        }
        var arr = [2, "Hello", 123.5, true, person];

        document.write("Type of array : " + typeof arr + "<br />");
        document.write("arr[0] : " + arr[0] + " type : " + typeof arr[0] + "<br />");
        document.write("arr[1] : " + arr[1] + " type : " + typeof arr[1] + "<br />");
        document.write("arr[2] : " + arr[2] + " type : " + typeof arr[2] + "<br />");
        document.write("arr[3] : " + arr[3] + " type : " + typeof arr[3] + "<br />");
        document.write("arr[4] : " + arr[4].firstName + " type : " + typeof arr[4] + "<br />");
    </script>
</body>

</html>

Open above page in browser, you can able see following data.

Type of array : object
arr[0] : 2 type : number
arr[1] : Hello type : string
arr[2] : 123.5 type : number
arr[3] : true type : boolean
arr[4] : Hari krishna type : object

Previous                                                 Next                                                 Home

No comments:

Post a Comment