JavaScript - Data Types

It is not necessary to define the data type when initializing the variables in Javascript. It automatically gets the data type of the variable according to the value stored in the variable. That is calling Dynamic Type Variables. Therefore Same  variable can be used to store following kind of data in JavaScript
1. String
    A set of characters can be stored by putting between the Double Quotes or Single Quote
    Syntax:
    var <variable name> = '<Value>' OR
    var <variable name> = "<Value>"

    Ex:
    var student = "John"; // OR
    var student = 'John';   

    var Relationship= "John's car"; // Can put single Quotes within Double Quotes 
    var car = 'John has "Toyota" car'; // Can put Double Quotes within Single Quotes

2. Number
    Numbers in the can be written with or without decimal places.
    var no1 = 50;
    var no1 = 53.25;


3. Boolean
    Boolean variables can be stored either true or false values
    Ex:
    var male = true;
    var female = false;

4. Array
    Array can be used to set of values in a single variable. 
    Syntax:
    var <variable name> = new Array(); // Defines the array variable
    <variable name>[0] = <Value>; // Assign a value to 1st position of the array
    <variable name>[1] = <Value>; // Assign a value to 2nd position of the array
    <variable name>[2] = <Value>; // Assign a value to 3rd position of the array....

    OR
    var <variable name> = new Array("<Value>","<Value>", "<Value>");

    OR
    var <variable name> =["<Value>","<Value>", "<Value>"];

    Ex:
    var country = new array(); // Defines the Country array
        country[0] = "Japan"; // Assign Japan to 1st position of the array
        country[1] = "India"; // Assign India to 2nd position of the array
        country[2] = "USA"; // Assign USA to 3rd position of the array
        country[3] = "Canada"; // Assign Canada to 4th position of the array
    OR
     var Numbers = new array(5, 10, 15, 20);

    OR
     var Numbers = [5, 10, 15, 20];

5. Object
    you can define objects in JavaScript with curly braces. Properties of the object can be 
    defined as named value pairs.
    Syntax:
    var <object name> = {<object Property 1>: <value >, <object Property 2>: <value >}

    Ex:
    var car = {Brand : "Toyota", Model : "Carina", Year = 2005 }

6. Undefined or Null
    Variables in JavaScript can be define with empty or no value.
    var name = null;

No comments:

Post a Comment