"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:

<!-- Prototype_typeof_Operator.html
   Copyright (c) 2008 HerongYang.com. All Rights Reserved.
<title>"typeof" Operator</title>
<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;

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

Table of Contents

 About This Book

 Introduction to JavaScript

 ECMAScript Language Specification and JavaScript Dialects

 Data Types, Variables and Expressions

 Flow Control Statements

 Creating, Accessing, and Manipulating Arrays

 Defining and Calling Functions

 Web Browser Supporting JavaScript

 Server-Side and Client-Side Web Scripting

 Introduction to Objects

Defining Your Own Object Types

 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

 Inheritance of Properties and Methods through the Prototype Object Chain

 'jrunscript' - JavaScript Shell Command from JDK

 Using Functions as "Function" Objects

 Introduction to Built-in Object Types

 W3C's Document Object Model (DOM) Specifications

 AJAX (Asynchronous JavaScript And XML)


 Full Version in PDF/EPUB