Question

I am aware of being able to use typeof, however, i would like to know if using

String(anyVariable) === anyVariable

in order to figure out if anyVariable is a string:

  • Is a generally valid approach?
  • Works consistently among browsers?
  • Has any pitfalls?
Was it helpful?

Solution 2

I can think of no reason to use your method vs. the much simpler typeof. Yours is likely to perform worse (15x slower by Matti's jsperf) and be more complex.

Your method is going to require multiple memory manipulations (creating string object, then assign string value to it) and then need to run the garbage collector afterwards whereas typeof just looks at a property of the internal javascript object.

When in doubt, choose the simplest method that solves your problem.

When in doubt, choose the method that is specified in the language definition for solving your problem.

When in doubt, choose the method that requires less memory manipulation.

OTHER TIPS

I would say do not do that, and use typeof because "String" is used to manipulate a stored piece of text, not compare types. It is best to use the features in their intended use, to assure the most stability, and best practice out of it. Also, the purpose is to extend the type with methods. So you are basically causing more work and processing, instead of just a type comparison. Hopefully that answers it, though this is a question that merely has an "opinion" as an answer. You wouldn't create a new object, assign it to your current object, to check if it is a type of object would you? No, you would just use "typeof".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top