JavaScript checking if variable is defined: typeof Operator
The typeof operator in JavaScript returns the datatype of an operand. Consider the examples below:
document.write(typeof 10);//number
document.write(typeof 'JS');//string
document.write(typeof new Date());//object
document.write(typeof myVar);//undefined
The final line of the examples above illustrates that if a variable has not been defined, the typeof operator will return undefined. A JavaScript program can take advantage of this fact to test for the existence of a variable, as follows:
if (typeof myVar == 'undefined')
document.write('variable undefined');
else
document.write('variable defined');
Other notes about the typeof operator:
The typeof operator returns boolean for the true and false values:
document.write(typeof false); //boolean
The typeof operator returns object for the null keyword:
document.write(typeof null);//object
For object properties, the typeof operator returns the type of the property:
document.write(typeof Math.PI);//number
For functions or methods, the typeof operator returns ‘function’:
var aryTest = [1,2,3,4];
document.write(typeof aryTest.splice);//function
May 5, 2008 at 7:02 am
Thanks for the simple explanation
Very helpful
February 3, 2009 at 10:48 pm
Thanks,
your explanation is simple and easy to understand.
March 15, 2009 at 4:11 am
ok thx bos
July 6, 2009 at 11:04 pm
Thank you for the post. This was exactly what I needed.