3

I am building a function to match types of variables. It will be an alternative to typeof <var> === "something".

My function call looks like this : is("some text")["string"]. It returns true, or is([])["element"]. Now it returns false, But I have an issue with it.

For example, if I try to send an undefined variable like "undefVar" to a function I am expecting something like this: is(undefVar)["undefined"], but I get an error which says that "undefVar" is not defined.

Can I somehow make my function work using undefined variables? Is this possible at all?

p.s: I have to use this function a lot so it seems (for me) that it would be better to use something like this : is(var)[type] as opposed to typeof var === type.

dsgriffin
  • 66,495
  • 17
  • 137
  • 137
John
  • 7,500
  • 16
  • 62
  • 95
  • 2
    A better solution is to simply not to allow malformed code by using variables before they have been declared. If you accidentally do, take advantage of the error message you get, and fix your broken code. Error messages are there to help you. They shouldn't be suppressed. – I Hate Lazy Oct 01 '12 at 13:47

2 Answers2

1

typeof is special on nonexistent variables. You cannot mimic it with a function.

Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
1

No, you cannot blindly pass undefined variables to your function from the call site and globally change the behavior of the JS engine to accomodate this.

typeof is a built-in operator and is not bound by the rules of "common" functions, which is why it can do things that custom functions cannot.

Finally, I strongly disagree that it would be practically preferable to use an alternative syntax even if that were possible.

Jon
  • 428,835
  • 81
  • 738
  • 806