Friday, January 3, 2014

Data Types In JavaScript

You may also like to see:

JavaScript is a dynamic typed (or termed as Loosely Typed) scripting language which means that same variable can be assigned data of different types.

Here is example (JsFiddle):

var dynamicVariable;               // Now dynamicVariable is undefined
dynamicVariable = 10;           // Now dynamicVariable is a Number
dynamicVariable = "Hello JavaScript";// Now dynamicVariable is a String
dynamicVariable = true         //Now dynamicVariable is a boolean

Variables in JavaScript is initialized with var keyword instead of data type itself like C, C++, C# or Java.

There are six Data Types in JavaScript, three of them are Primitive or also known as Primary data type while everything else in JavaScript is Object or Reference Typed also known as Composite data types.

Primitive Data Types:

The primitive data types are (JsFiddle):
  • String
  • Number
  • Boolean
Reference Data Types

Other than above three primitive data types everything in JavaScript is object like function, Regexp etc. The reference data types are (JsFiddle):
  • Object
  • Array
  • Function

In JavaScript specifications typeof Array and null is object, so to confirm whether object is Array or null you can use

console.log(Object.prototype.toString.call(new Array("test","items"))); //will print [object Array]
console.log(Object.prototype.toString.call(null)); //will print [object Null]

Special Data Types:


There are two others special data types, which includes (JsFiddle):
  • null
  • undefined

String Data Type

String data type is use to represent text in JavaScript. A string is value with zero or more characters which may include letters, punctuation marks and digits. There is no separate data type for character (char) in JavaScript. You may use single or double quote for assigning value to string.

These are some examples of valid string data types in JavaScript:

var str1 = "Hi, How are you?";
var str2 = "He said: 'Hi'";
var str3 = 'He said:"Hi" ';
var str4 = "25";
var str5 = "";
var str6 = 'C';

In JavaScript you may get the data type of any variable using typeof

alert(typeof str1);

using type of on above all variables will return you string. Here is demo (JsFiddle).

Number Data Type

For any numeric values float, decimal or integer JavaScript has only one data type that is Number.

Here are some examples (JsFiddle):

var num1 = 23;   //integer value
var num2 = 42.25; //float value
var num3 = 22e5; //exponential 2200000
var num4 = 13e-5 //0.00013

Additional special value for numeric types are :
  1. NaN (not a number) to represent inappropriate data, as a result of mathematical operation
  2. Positive Infinity represents too large positive number
  3. Negative Infinity represents too large negative number
  4. Positive and Negative 0 represent positive and negative zero(JavaScript differentiate zero as positive or negative).
Boolean Data Type

Boolean data type can only have two values, literals true and false. Comparison of two variables will outcome a Boolean value. Boolean are used for condition testing.

Here is example (JsFiddle):
var num1=54; 
var result = (num1 === 2000); //will return false
var result1 = (num1 === 54); //will return true


Primitive variables as Objects

In JavaScript all variable can be of object type, for each primitive their is a Object type. You can initialize object type by using new keyword with String, Number or Boolean. It will initialize object of that type.
var str = new String; //default value is empty string ""
var num = new Number; //default value is 0
var bool = new Boolean; //default value is false

Object Data Type

Object data type is a custom data type, it can be assumed a class of object oriented language. It may contains many properties or function. Object is defined in curly braces, in these braces properties and function are defined as key-value pair.

Here is example (JsFiddle):

var person = {
    Id: 1,
    FirstName: "firstname",
    LastName: "lastname",    
    Walk: function () {
        alert("walk using two legs");
    }
};

Properties and functions can be access by property or function name with variable i.e, person.FirstName; or person.Walk().


Array Data Type

Array is collection containing zero or more items. Array items can be access by using indexing on variable. In JavaScript specifications typeof Array is object, which cause confusion. Array can be initialize in different ways.

Here are examples (JsFiddle):

var dataTypes=new Array();
dataTypes[0]="String";
dataTypes[1]="Number";
dataTypes[2]="Boolean";

//condensed array:
dataTypes=new Array("String","Number","Boolean");

//literal array:
dataTypes=["string","number","boolean"]; 


Function Data Type

In JavaScript variable may also be a function, which can be trigger using round bracket. These type of variable can be initialize by assigning function to a variable.

Here is example (JsFiddle):

var myFunc = function(){
  alert("function is triggered");
}; 

myFunc();

Null Data Type

The value for null data type can only be null. keyword null is use to assign null to any variable. It can be use to emptied content of any variable without deleting the variable. A variable with null data type contains no valid other data types.
Like Array in JavaScript typeof operator with null returns the object which is confusing behavior.

Here is example (JsFiddle):

var type = null;
var obj = null;

Undefined Data Type

The undefined value is default for a variable which is declared but never assigned a value.

Here is example (JsFiddle):

var myVar;
if((typeof var) === "undefined"){
  alert("variable is undefined");

In JavaScript best practice is to use triple-equals-operator for comparison. Detailed article here.

You may also like to see:

2 comments:

  1. can we define data type with string or int keyword?

    ReplyDelete
    Replies
    1. No, we can't. we can only define it by var keyword.

      Delete