In JavaScript sometimes we need to know the type of a given variable. Being a loosely typed language, JavaScript offers only a basic implementation of the more advanced features of other classical OO languages. The typeof
operator, in fact, is rather misleading in the sense that most of the times it simply returns Object
as its value. As you know, in JavaScript numbers and arrays are objects, as well as functions and strings. The problem is that with the aforementioned approach we can't determine the type of the first two. But there's a solution.
You can call the toString()
method of Object
on a given variable to see what's the output returned by the browser:
var arr = ['a', 1, true]; console.log(Object.prototype.toString.call( arr )); // '[object Array]'
By using this approach, you can test as many types of variables as you want.