Sunday, September 23, 2012

Type Checking in JavaScript

We have only few types in JavaScript those are 
  1. Number 
  2. String
  3. Boolean
  4. Undefined
  5. Null
  6. Object
JavaScript is a loosely typed language. same variable can take different types in different situations. because of this reason it's better to have a type checking functionality in the scripts.

With the typeof operator you can check a variable type. instaceof operator yields true or false whether a given type is an instance of particular type.

You can create object wrappers for number, string, and Boolean datatypes.

//Number
var myNum = 10;
console.log(myNum); //10
console.log(typeof myNum); //number


var myNewNum = new Number(10);
console.log(myNewNum); //10 console.log(typeof myNewNum); //object
myNewNum.constructor; //Number() 
 
//string
var myStr = "srinivas";
console.log(myStr); //srinivas
console.log(typeof myStr) //string
 
var myNewStr = new String("srinivas");
console.log(myNewStr); //String{0="a",1="r" 2="i", more...}
console.log(typeof myNewStr) //Object
myNewStr.constructor //String() 
 
//Boolean
var myBool = true;
console.log(myBool); //true
typeof(myBool); //boolean
 
var myNewBool = new Boolean(true);
console.log(myNewBool); //Boolean{}
console.log(typeof myNewBool); //Object

//Object
var myObj ={};
typeof(myObj) //object
alert(myObj.constructor) //function Object() {[native code]}
 
var myNewObj = new Object();
typeof(myNewObj) //object
alert(myNewObj.constructor) //function Object() {[native code]}
 
What about arrays? JavaScript arrays are objects
 
var myArray = [];
typeof(myArray) //object
alert(myArray.constructor)//function Array() {    [native code]}

var myNewArray = new Array();
typeof(myNewArray); //object
alert(myNewArray.constructor) //function Array() {    [native code]} 

so how can you check a given type is an array or not?In ECMAScript5.0 onwards Array methods included isArray methods. It yields a Boolean value.
var myArray =[];
Array.isArray(myArray);

We have compatibility issues with isArray() method. So how can we check is it’s an array or not? 

myArray  Instanceof Array //true


No comments:

Post a Comment