0

In JavaScript, variables are loosely typed, so the number 5 and the string "5" may both be treated as a number by several operators. However, is there a generic way to find out JavaScripts conversion abilites in at tunrime, or is it just the overloading of operators for several types that make the loose typing possible?

For example, given a variable a and a string containing a type name type_canditate, is there any way to ask JavaScript, if a may convert to type_candidate in a feasable manner, in contrast to the hard typing operators like instanceof? For example, "5" instanceof Number evaluates false, while Math.sin("5") is perfectly feasable. For numbers, one can obviuosly check if parseFloat(some_number) evaluates to NaN, but this is a special case for numbers.

So, is there any generic way of naming types, and check if some variable may convert to a given type in a useful manner?

9
  • There's no facility expressly for that purpose, but you can always attempt a conversion to a type from any other type to see what you get. Commented Feb 28, 2014 at 15:32
  • Also, parseFloat() is not a good way to check for convertability. The Number() constructor is safer. Commented Feb 28, 2014 at 15:33
  • What are the benefits of Number over parseFloat? Commented Feb 28, 2014 at 15:34
  • Try in your browser console parseFloat("23skidoo"); Commented Feb 28, 2014 at 15:35
  • Ok, but try Number(''), it evaluates to 0. So both of these conversions do not discern numbers from non-numbers. What a mess... Commented Feb 28, 2014 at 15:55

1 Answer 1

1

There are three primitive data types in JavaScript: string, number and boolean.

Anything can be converted to a string or boolean:

  • All objects convert to true (except null, which becomes false - I only mention it here because typeof null gives object)
  • All objects have a built-in toString method which is called when converting to a string.
  • Converting a number to a string is done by giving the string representation of the number (ie. 5 becomes "5")
  • Numbers convert to boolean true, unless it's 0 which becomes false.

Converting to a number is a little trickier, but technically possible. If it can find a valid number, then it becomes that number. Otherwise, it becomes NaN.

So basically... any type can become any other type through casting in this way. The only time you have anything resembling an "error condition" is NaN.

Sign up to request clarification or add additional context in comments.

2 Comments

Objects are converted to numbers via the valueOf() function, which is basically the number analogue of toString().
Just asked another question about checking for numbers: stackoverflow.com/questions/22100243/…

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.