JavaScript get the type of variable | typeof or instanceof method example

Use typeof method to get a type of variable in JavaScript. But typeof is only good for returning the “primitive” types such as number, boolean, object, string, and symbols. You can also use instanceof to test if an object is of a specific type.

Example of JavaScript get the type of variable

HTML example code:-

Use typeof:

HTML example get the type of variables in JavaScript.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        var num = 50;
        var str = "Hellow";

        console.log(typeof(num));
        console.log(typeof(str));
    </script>
</head>
<body>
 
</body>
 
</html>

Output:

JavaScript get the type of variable

Console code .

> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"

Another interesting way is to examine the output of Object.prototype.toString:

> Object.prototype.toString.call([1,2,3])
"[object Array]"
> Object.prototype.toString.call("foo bar")
"[object String]"
> Object.prototype.toString.call(45)
"[object Number]"
> Object.prototype.toString.call(false)
"[object Boolean]"
> Object.prototype.toString.call(new String("foo bar"))
"[object String]"
> Object.prototype.toString.call(null)
"[object Null]"
> Object.prototype.toString.call(/123/)
"[object RegExp]"
> Object.prototype.toString.call(undefined)
"[object Undefined]"

The typeof method is only good for returning the “primitive” types such as number, boolean, object, string, and symbols. You can also use instanceof to test if an object is of a specific type.

function MyObj(prop) {
  this.prop = prop;
}

var obj = new MyObj(10);

console.log(obj instanceof MyObj && obj instanceof Object); // outputs true

Do comment if you have any doubts and suggestions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

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