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

One Response

  1. Thanks for the simple explanation :)

    Very helpful

Leave a Reply