DEV Community

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

 
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
 
blessinghirwa profile image
Blessing Hirwa

That's a good example Gil. Thanks 😁

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