Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)
Can anyone help me how I can able to find the variable type in JavaScript? As in Java, we can use instanceOf() and getClass() method.

1 Answer

0 votes
by (26.7k points)

You can use typeof to get the variable type:

if(typeof bar === 'number') {

   //whatever

}

Also, you can use 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]"

I hope this will help.

Want to become a Java Expert? Join Java Training now!!

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...