We know that JavaScript is a dynamically typed language, but remember, this doesn't mean that JavaScript is void of types.

JavaScript absolutely has types that back its variables, we're just sort of “abstracted” out of that process by its magic and wizardry. Okay it's not magic, it's just code, but it can seem like magic at times right?

So the real question here is, how can we determine the type that is assigned to any given variable?

Determining a Variable's Type in JavaScript

Thankfully, JavaScript makes it easy to determine the type that backs any of your variables.

It's called the typeof keyword.

Here's an example of how it's used:

  var myVariable = "What's my type?";
  alert("myVariable's type is: " + (typeof myVariable));

Here's the result:


There you have it! The type of myVariable is string.

So to determine any variable's type in JavaScript, you just need to put the typeof keyword before a variable and it will return a string that describes the variable's type.

Examples of typeof Keyword

var anObj = {someProperty: "Just an example"};

if (typeof anObj == 'string')
  alert("Our variable is a string");
else if (typeof anObj == 'object')
  alert("Ladies and gentlemen, we have an object!");

In Summary

There's really not much to the typeof keyword as you can see. It's quite straight forward to use and it just “works” like you'd imagine it would. Phew!

What may help you out is to know the different types that can be assigned to any given variable, so if you're fuzzy on the list, just check out this article to help refresh your memory.

And hey, don't forget to sign up for our mailing list below. I'm always giving out awesome free stuff and get such great feedback from my students with respect to how much they love what I send out. So it's likely worth your time and I promise never ever ever ever to sell or give away your information to anyone, that kind of business is just too sleazy for me!

Free Java Roadmap

Discover exactly what you need to learn and where to start in order to become a professional coder.