Javascript typeof Operator

JavaScript typeof operator returns a string which indicates the type of an operand. typeof operator always returns string value. JavaScript typeof operator returns six possible values from “number,” “string,” “boolean,” “object,” “function,” and “undefined.”


typeof operator is mostly used with condition statements to check the type of variable before going further in execution to stop any exceptions.
It would be a good practice to check for type of variable is not undefined before doing any mathematical operation, otherwise it produces unexpected results. Brackets are optional.

	typeof (operand)

Below table shows the possible return values of typeof operator.

Type			Result
Undefined		"undefined"
Null			"object" (see below)
Boolean			"Boolean"
Number			"number"
String			"string"
Function object 	"function"
Any other object	"object"

<!DOCTYPE html>

Default Value is not set for locationName variable

<p id="demo"></p>

var locationName;
if(typeof locationName == 'undefined') {
	alert('Variable locationName is undefined');



Download the codeRun the code

Examples of typeof comparison

// Numbers
typeof 55 === ‘number’
typeof 55.5 === ‘number’
typeof NaN === ‘number’
// Output: true

typeof “” === ‘string’
typeof “test” === ‘string’
// Output: true

typeof true === ‘boolean’
typeof false === ‘boolean’
// Output: true

typeof undefined === ‘undefined’;

// Objects
typeof {country:’US’} === ‘object’;
typeof [1, 2, 3, 4] === ‘object’; // typeof array returns object

typeof function(){} === ‘function’;
// Output: true

typeof null === ‘object’

<<< Javascript ternary operatorJavascript Arithmetic Operators >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .