DEV Community


Discussion on: 8 neat Javascript tricks you didn't know in 4 minutes.

sureshvv_37 profile image

Economy of expression. Strength of any language is how well it can express ideas in a well understood and succinct manner. Unary plus (+) is now a type conversion operator with well defined semantics,

Thread Thread
gilfewster profile image
Gil Fewster

One reason why you may favour unary plus over parseFloat/parseInt is to protect against incorrect results if the string you're attempting to convert contains one or more thousands separator commas or more than 1 decimal point:

const str = "6,750";
const str2 = "6750.45.99";
console.log(parseFloat(str)) // 6
console.log(parseFloat(str2)) // 6750.45
console.log(+str) // NaN
console.log(+str2) // NaN
Enter fullscreen mode Exit fullscreen mode

I'd typically prefer to sanitise the data before attempting type conversion, but I still like that the unary plus operator refuses to take a guess when given an ambiguous input.

Thread Thread
blessingartcreator profile image
Blessing Hirwa Author

That's a good example Gil. Thanks 😁

Some comments have been hidden by the post's author - find out more