Javascript Typeof Example

When writing code in whatever programming language, you will inevitably have to deal with different types of variables and treat them accordingly. What happens when you are not the one who defines your variables type? Let’s have a look!

Typeof syntax

typeOf can be used in two ways: as a function and as an operator. Though the syntax changes a bit, it is mainly the same. Here’s how you use it in function form:


And this is how you use it in the operator form:

typeof myVar;

Obviously, typeof will take a value and return it’s type.

As we all know, there are several primitive types in Javascript:

  • string
  • such as “Twinkle twinkle” and “little star”

  • boolean
  • true and false values

  • number
  • all numbers and pseudo-numbers such as 3.14, infinity and NaN (which ironically means Not-A-Number!)

  • object
  • which includes functions and arrays

  • null, undefined
  • which contains every special value of variables that does not fall into the above categories

Let’s see this operator in action in the code snippet below:

typeof 7.5   // "number"

typeof NaN  // "number"

typeof false // "boolean"

typeof "wcg" // "string"

typeof undefined // "undefined"

typeof {} // "object"

typeof null  // "object"

typeof function(){} // "function"

You will have noticed that while the typeof operator correctly guesses that 7.5 is a number, it considers NaN as a number too. It works correctly for boolean and string values, and also attributes the “undefined” type to undefined, but then considers null and object too when it’s officially not an object. Also, functions are getting special treatment by Javascript, when they are objects.

However it may seem a bit problematic, if you just remember these small issues, you will not only be able to overcome them, but also use them to your advantage.

Download the source code

This was an example of typeof in Javascript.

Download the source code for this tutorial:

You can download the full source code of this example here: TypeOf

Do you want to know how to develop your skillset to become a Web Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. Building web apps with Node.js

2. HTML5 Programming Cookbook

3. CSS Programming Cookbook

4. AngularJS Programming Cookbook

5. jQuery Programming Cookbook

6. Bootstrap Programming Cookbook


and many more ....


I have read and agree to the terms & conditions


Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button