Wednesday, February 5, 2014

JavaScript: typeof

The typeof is an operator in JavaScript. 
It gets the data type of the variable. 
It returns a string value mentioning the datatype of the string. 
The operand can be a value, function or an object.

The following are the six possible typeof returns;

object
boolean
function
number
string
undefined

Syntax:

var sName = 'JavaScript';

//Usage format #1
alert(typeof sName);    //Will display string

//Usage format #2
alert(typeof(sName));    //Will display string


Tip: Always use the strict compare "===" when sing the typeof in a conditional operation.

Example:

var sName = 'JavaScript';

if(typeof(sName) === 'string')
{
    alert('The variable is a String');
}

Trivia: typeof(null) returns object