Tuesday, January 29, 2013

typeof operator in javascript!!

The typeof operator in javascript is used to find the data type of the variables or operands. typeof returns a string which includes any one of the below list.
  • number: it returns this string if the input to the typeof is number
  • string: it returns this string if the input to the typeof is string
  • boolean: it returns this string if the input to the typeof is boolean
    • The string is boolean and not bool
  • object: it returns this string if the input to the typeof is javascript
  • undefined: it returns this string if the input to the typeof is a variable and which is not defined
Syntax:
 typeof operand // braces are optional
 typeof(operand)

Example:
 typeof 2 //returns number
 typeof(2) //returns number
 typeof("2") // returns string
 typeof(a) // a is a variable and returns depending on a value

Sample code:
function typetest()
{
 var a = 2; //number type
 var a = "2"; // string type
 var a; //undefined
 var a = true; //boolean type
 var a = {a:"first character",b:"second character"}; // object type
 if(typeof a == "number")
 alert("a is number");
 else if(typeof a == "string")
 alert ("a is string");
 else if(typeof a == "undefined")
 alert ("a is undefined"); 
 else if(typeof a == "boolean")
 alert ("a is boolean"); 
 else if(typeof a == "object")
 alert ("a is object"); 
}

This function gives object as output, because javascript overrides the variable declarations, so latest declaration will take, here it is javascript object. This variable overriding is called variable hoist. I will write one post on this later.

Subscribe to: Comments (Atom)

Popular Posts

AltStyle によって変換されたページ (->オリジナル) /