0
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?

3
  • What is wrong with typeof? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Oct 9, 2013 at 15:41
  • I think you should define what you would class as a "flaw" Commented Oct 9, 2013 at 15:47
  • I’d say the main flaw in this approach is that you assume that the result of the toString method of any given object that you might pass into that function would be the exact same text in every given browser … Commented Oct 9, 2013 at 15:52

2 Answers 2

2

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"
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry - too quick to vote. Before your edit it really didn't look like an answer. Vote retracted.
No worries, shouldn't have typed the response, then Ctrl+A/V the console output. I'm not a smart man.
-1

Yes. there is a keyword typeof

e.g

var abc = typeof variablename;

here abc will contain type of variable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.