Visit Mozilla.org

Core JavaScript 1.5 Reference:Operators:Special Operators:typeof Operator

From MDC


[edit] Summary

The typeof operator is used in either of the following ways:

  1. typeof operand
  2. typeof (operand)

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

Operator
Implemented in: JavaScript 1.1
ECMA Version: ECMA-262

This table summarizes the possible return values of typeof:

Type Result
Undefined "undefined"
Null "object"
Boolean "boolean"
Number "number"
String "string"
Host object (provided by the JS environment) Implementation-dependent
Function object (implements [[Call]] in ECMA-262 terms) "function"
Any other object "object"


[edit] Examples

Suppose you define the following variables:

var myFun = new Function("5+2")
var shape="round"
var size=1
var today=new Date()

The typeof operator returns the following results for these variables:

typeof myFun == 'function'   
typeof shape == 'string'
typeof size == 'number'
typeof today == 'object'
typeof dontExist == 'undefined'

For the keywords true and null, the typeof operator returns the following results:

typeof true == 'boolean'
typeof null == 'object'

For a number or string, the typeof operator returns the following results:

typeof 62 == 'number'
typeof 'Hello world' == 'string'

For property values, the typeof operator returns the type of value the property contains:

typeof document.lastModified == 'string'
typeof window.length == 'number'
typeof Math.LN2 == 'number'

For methods and functions, the typeof operator returns results as follows:

typeof blur == 'function'
typeof eval == 'function'
typeof parseInt == 'function'
typeof shape.split == 'function'

For predefined objects, the typeof operator returns results as follows:

typeof Date == 'function'
typeof Function == 'function'
typeof Math == 'object'
typeof Object == 'function'
typeof String == 'function'

[edit] Specification

ECMA-262 section 11.4.3