Saturday, 1 September 2018

JavaScript: Sparse arrays

In sparse arrays, elements need not have contiguous indexes.

var arr1 = new Array();
arr1[100] = "Hello";
arr1[1234] = 432156;

Eventhough we entered only two elements into the array arr1, the length of the array is 1235 (maximum index + 1 = 1234+1).

sparse.html
<!DOCTYPE html>

<html>

<head>
    <title>sparse arrays</title>
</head>

<body>
    <script type="text/javascript">
        var arr1 = new Array();
        arr1[100] = "Hello";
        arr1[1234] = 432156;

        document.write("arr1 length : " + arr1.length);
    </script>
</body>

</html>

Open above document in browser, you can able to see following text.

arr1 length : 1235

For dense array the length of the array is equal to number of elements in the array, where as for sparse arrays the length of the array can be greater than the number of elements in the array.

Previous                                                 Next                                                 Home

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

JavaScript: Define array using Array constructor function

In my previous post, I explained how to create an array using literal([]) notation. you can even define an array using Array constructor function.

var arr1 = new Array()
Above statement creates an empty array.

var arr2 =  new Array(10)
Above statement creates an array of size 10.

In addition to above, we can specify array by passing elements of array as arguments to constructor function.

var arr3 = new Array(1, 123.45, 5, 43);


Previous                                                 Next                                                 Home

JavaScript: Array

Array is an ordered collection of elements.

Syntax
var arrayName = [elem1, elem2 .... elemN];
var arrayName = new Array(size)

How to access element of an array?
By using index notation, you can access element of an array. Index starts from 0.

Syntax
arrayName[index]

arr[0] : Return the first element
arr[1] : Return 2nd element
…..
…..
arr[n] : Return n-1th element

array.html

<!DOCTYPE html>

<html>

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

<body>
    <script type="text/javascript">
        var arr = [2, "Hello", 123.5, true];

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

</html>

Open above page in browser, you can able to see following data.
arr[0] : 2
arr[1] : Hello
arr[2] : 123.5
arr[3] : true
arr[4] : undefined
object

What is the maximum index number in array?
Arrays in javaScript use 32-bit indexes. So the maximum array index number is ((2^32)-2) = 4294967294 (Since arrays are zero indexed).



Previous                                                 Next                                                 Home

JavaScript: Serialize objects

Serialization is the process of converting object state to string. de-Serialization is a process to bring back the object’s state from string. JavaScript provides JSON.stringify() to serialize the object and JSON.parse() method to deserialize.

serialize.html
<!DOCTYPE html>

<html>

<head>
    <title>Serialization</title>
</head>

<body>
    <script type="text/javascript">
        function displayObject(obj) {
            document.write("<br />");
            for (prop in obj) {
                document.write(prop + " : " + obj[prop] + "<br />");
            }
            document.write("<br />");
        }

        function Employee(id, firstName) {
            this.id = id;
            this.firstName = firstName;
        }

        var emp1 = new Employee(1, "Hari Krishna");
        document.write("emp1 details");
        displayObject(emp1);

        var serializedData = JSON.stringify(emp1);
        document.write("<br />Serialized data is " + serializedData + " <br /><br />");

        var emp2 = JSON.parse(serializedData);

        document.write("emp2 details");
        displayObject(emp2);
    </script>
</body>

</html>


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


emp1 details
id : 1
firstName : Hari Krishna


Serialized data is {"id":1,"firstName":"Hari Krishna"}

emp2 details
id : 1
firstName : Hari Krishna

What data types of JavaScript are supported while serialization?
Currently JSON syntax is a subset of JavaScript syntax. Objects, arrays, strings, finite numbers, true, false, and null are supported and can be serialized and deserialized.

What about special values NaN, Infinity, -Infinity?
NaN, Infinity, and -Infinity are serialized to null.

How the Date objects serialized?
Serialized in the form of ISO-formatted date strings.

Is there any objects that I can’t serialize?
Function, RegExp, and Error objects and the undefined value cannot be serialized (or) deserialized.

Is non-enumerable properties serialzed?
No, only enumerable properties of an object are serialized.



Previous                                                 Next                                                 Home

Convert string to JavaScript object

By using JSON.parse method, you can convert JSON string to JavaScript object.

object.html
<!DOCTYPE html>
<html>

<head>
    <title>Convert string to JSON object</title>
</head>

<body>
    <div id="data">

    </div>

    <script type="text/javascript">
        var str = '[{"firstName":"Hari Krishna","lastName":"Gurram","age":27},{"firstName":"Kiran Kumar","lastName":"Darsi","age":28}]';

        var employees = JSON.parse(str);

        var result = "";

        for (var i = 0; i < employees.length; i++) {
            result += ("firstName : " + employees[i].firstName + "<br />");
            result += ("lastName : " + employees[i].lastName + "<br />");
            result += ("age : " + employees[i].age + "<br /><br />");
        }

        document.getElementById("data").innerHTML = result;
    </script>
</body>

</html>

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

firstName : Hari Krishna
lastName : Gurram
age : 27

firstName : Kiran Kumar
lastName : Darsi
age : 28


Previous                                                 Next                                                 Home

JavaScript: Convert javascript object to json string

JSON.stringify(object) method converts JavaScript object to JSON string.

stringify.html
<!DOCTYPE html>
<html>

<head>
    <title>Convert Java object to string</title>
</head>

<body>
    <h1>String format of employees object is</h1>
    <div id="data">

    </div>

    <script type="text/javascript">
        var employees = [{
            "firstName": "Hari Krishna",
            "lastName": "Gurram",
            "age": 27
        }, {
            "firstName": "Kiran Kumar",
            "lastName": "Darsi",
            "age": 28
        }];

        var str = JSON.stringify(employees);
        document.getElementById("data").innerHTML = str;
    </script>
</body>

</html>

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

String format of employees object is

[{"firstName":"Hari Krishna","lastName":"Gurram","age":27},{"firstName":"Kiran Kumar","lastName":"Darsi","age":28}]




Previous                                                 Next                                                 Home