DEV Community

Discussion on: ✔||🤢 Commit or Vomit | + cast

Collapse
edave64 profile image
edave64

This implicit cast is equal to Number(numberInputField.value), not parseInt or parseFloat, like some in the comments suggest. Since all of javascripts typing is odd, this has some interesting edge cases, e.g:

+"0x4" //=> 4
parseFloat("0x4") //=> 0

+[] //=> 0
parseFloat([]) //=> NaN

+null //=> 0
parseFloat(null) //=> NaN

+[12] //=> 12
parseFloat([12]) //=> 12

+[12, 12] //=> NaN
parseFloat([12, 12]) //=> 12

+{} //=> NaN
parseFloat({}) //=> NaN

+{ valueOf () { return 12 } } //=> 12
parseFloat({ valueOf () { return 12 } }) //=> NaN

+Symbol("12") //=> TypeError: Cannot convert a Symbol value to a number
parseFloat(Symbol("12")) //=> TypeError: Cannot convert a Symbol value to a string
Enter fullscreen mode Exit fullscreen mode

However, you are using TypeScript, so I might actually let this slip! Once your codebase is explicitly properly typed, explicit casts can be considered redundant information.

In this specific case, I tend to say: Neither. Use a custom cast, that validates the value fits your specific number format, since parseFloat just silently ignores garbage, which could lead to an unintended result. Which cast you use in that function at the end is fairly irrelevant.