Thursday 23 August 2018

JavaScript: Types

Types are used to represent the type of data. Primarily, there are two categories of types.
a.   Primitive types
b.   Reference types

Primitive Types
Numbers, strings and Boolean values considered as primitive types. In addition to these, special values null, undefined are also considered as primitive types.

Reference Types
Objects and arrays are considered as reference types. An object is a collection of name and value pairs. Array is a collection of elements.
One more thing to note is that JavaScript treats functions also objects.

types.html
<!DOCTYPE html>

<html>
 <head>
  <title>Data Types</title>
 </head>
 
 <body>
  <script>
   var a = 10;
   var b = 10.01;
   var c = true;
   var d = "Hello World";
   var e = {
    name : "Hari krishna",
    city : "Bangalore"
   };
   
   var f = [2, 3, 5, 7];
   
   document.write("a = " + a + " Type of a = " + (typeof a) + "<br />");
   document.write("b = " + b + " Type of b = " + (typeof b) + "<br />");
   document.write("c = " + c + " Type of c = " + (typeof c) + "<br />");
   document.write("d = " + d + " Type of d = " + (typeof d) + "<br />");
   document.write("e = " + e + " Type of e = " + (typeof e) + "<br />");
   document.write("f = " + f + " Type of f = " + (typeof f) + "<br />");
  </script>
 </body>
</html>

Open above page in browser, you can able to see following messages in the html page.

a = 10 Type of a = number
b = 10.01 Type of b = number
c = true Type of c = boolean
d = Hello World Type of d = string
e = [object Object] Type of e = object
f = 2,3,5,7 Type of f = object


As you see the output, JavaScript treats both integer and float values as type number and arrays, objects are treated as type object.

Previous                                                 Next                                                 Home

No comments:

Post a Comment