Friday, 24 March 2017

Data Type in JavaScript 

JavaScript has five primitive data type.

1  Number
2  String
3  Boolean
4  Undefined
5  Null

Any data type other than above 5 types is called object.  

In javascript there are two types to object.

  1. Build in object
  2. Custom object

Build in Object :  Examples include array, date etc. In below example we have create the object of date by using date constructor.

    var date= new Date();
    alert(date.getDate);
    alert(date.getFullYear);


Custom objects : In JavaScript we don't have classes. We use function instead of classes.
In JavaScript there are two ways to create a custom object.

1. Constructor function
2. Literal notation

Constructor Function

<script type="text/javascript">
    function Student(firstName, lastName)
    {
       this.firstName = firstName;
       this.lastName = lastName;

       this.getFullName = function ()
       {
           return this.firstName + " " + this.lastName;
       }
    }

    var student= new Student("Jitendra", "Kachhi");

    document.write("First Name :" + student.firstName + "<br/>");
    document.write("Last Name : " + student.lastName + "<br/>");
    document.write("Full Name :" + student.getFullName() + "<br/>");
</script>

literal Notation

<script type="text/javascript">
    var student=
    {
       firstName: "Jitendra",
       lastName: "Kachhi",

       FullName: function ()
       {
           return this.firstName + " " + this.lastName;
       }
    }

    document.write("FirstName = " + student.firstName + "<br/>");
    document.write("LastName = " + student.lastName + "<br/>");
    document.write("FullName = " + student.FullName() + "<br/>");
</script>

Note:- literal Notation will have only single object(singleton), if we want to create multiple object use Constructor Function.


Thanks you for reading.