JavaScript Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 2.10

"typeof" Operator and Data Types

This section provides a quick description of the 'typeof' operator and data types supported in JavaScript. A tutorial example is provided to list all data types number, string, boolean, object, function, and undefined.

In the previous section, we learned how to use the "instanceof" operator. But JavaScript offers another operator called "typeof", which works like "instanceof". Here is a comparison of them:

1. "object_name instanceof constructor_name" returns true if the specified object is an instance of the specified type.

2. "typeof expression" returns the data type name of the specified expression. Remember that JavaScript supports several data types: "number", "string", "boolean", "object", "function", and "undefined".

To show you those data types and how to use "typeof", I wrote this tutorial example:

<html>
<!-- Prototype_typeof_Operator.html
   Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>"typeof" Operator</title>
</head>
<body>
<pre>
<script type="text/javascript">
   // Creating an object of "Book"
   var myBook = new Book("JavaScript Tutorials", "Herong Yang");

   // Show different data types
   showDatatype(9, "9");
   showDatatype(3.14, "3.14");
   showDatatype("Hello", "\"Hello\"");
   showDatatype(true, "true");
   showDatatype(undefined, "undefined");
   showDatatype(null, "null");
   showDatatype(myBook, "myBook");
   showDatatype(Book, "Book");

function showDatatype(x, name) {
   document.writeln(name+": "+(typeof x));
}

function Book(title, author) {
   this.title = title;
   this.author = author;
}
</script>
</pre>
</body>
</html>

Here is the output of this tutorial example. Note that the data type of "null" is "object".

9: number
3.14: number
"Hello": string
true: boolean
undefined: undefined
null: object
myBook: object
Book: function

Sections in This Chapter

Prototype-Dased Object-Oriented Programming Style

Prototype-Based Programming Features in JavaScript

Defining Object Constructor Functions

Adding Properties and Methods to Objects

"for ... in" and "for each ... in" Statements

"prototype" Property of the Constructor Function Object

"instanceof" Operator - Determining Object Type

"typeof" Operator and Data Types

Dr. Herong Yang, updated in 2008
"typeof" Operator and Data Types