lichgo
lichgo

Reputation: 533

Simplest way to check the type of a variable in JavaScript

function type(arg) {
    return Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
}

Is there any flaw in the above code to check the type?

Upvotes: 0

Views: 66

Answers (2)

Nitish Kumar
Nitish Kumar

Reputation: 4870

Yes. there is a keyword typeof

e.g

var abc = typeof variablename;

here abc will contain type of variable

Upvotes: -1

Brian
Brian

Reputation: 7654

Really depends on what you want the function to return. There are slight differences between typeof and type().

> type('wat')
"string"
> typeof 'wat'
"string"
> type(window)
"global"
> typeof window
"object"
> type(document)
"htmldocument"
> typeof document
"object"

Upvotes: 2

Related Questions