Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to get type of a Javascript variable?

Is there a better way to get the type of a variable in JS than typeof? It works fine when you do:

> typeof 1
"number"
> typeof "hello"
"string"

But it's useless when you try:

> typeof [1,2]
"object"
>r = new RegExp(/./)
/./
> typeof r
"function"

I know of instanceof, but this requires you to know the type beforehand.

> [1,2] instanceof Array
true
> r instanceof RegExp
true

Is there a better way?

like image 854
Aillyn Avatar asked Oct 08 '22 10:10

Aillyn


People also ask

How do you get the datatype of a variable A in JavaScript?

typeof is a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well. The typeof operator is useful because it is an easy way to check the type of a variable in your code.

How do you determine the type of a variable?

To check the type of a variable, you can use the type() function, which takes the variable as an input. Inside this function, you have to pass either the variable name or the value itself. And it will return the variable data type.

Which operator is used to find the typeof a JavaScript variable?

JavaScript has a special operator called typeof which lets you get the type of any value. In this article, we will learn how typeof is used, along with a few gotchas to watch out for.

Does variable have type in JavaScript?

tl;dr: In JavaScript, variables don't have types, but values do. The above code is perfectly valid because in JavaScript, variables don't have types. Variables can hold arbitrary values, and these values have types. Think of variables as labeled boxes whose contents can change over time.


1 Answers

Angus Croll recently wrote an interesting blog post about this -

http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/

He goes through the pros and cons of the various methods then defines a new method 'toType' -

var toType = function(obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
like image 255
ipr101 Avatar answered Oct 10 '22 23:10

ipr101