DEV Community

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

Collapse
 
jkettmann profile image
Johannes Kettmann • Edited

These are all nice tricks but I wouldn't recommend using most of them on production code. +'123' for example just doesn't explain what's going on to anyone who's not familiar with the syntax

Edit: "most of them" was exaggerated to be fair. 1,2, and 8 wouldn't pass a code review from my perspective. 3 would be critical, but it might be a nice way when wrapped in a descriptive function

Collapse
 
sureshvv_37 profile image
sureshvv

No one would write +"123". They may as well write 123.

But they may write value = +value instead of value = parseInt(value)

And that would be a win!

Collapse
 
jkettmann profile image
Johannes Kettmann

How would that be a win?

Thread Thread
 
sureshvv_37 profile image
sureshvv

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

That's a good example Gil. Thanks 😁

Collapse
 
blessinghirwa profile image
Blessing Hirwa

These tricks are used by some people, so it's better to know them so that whenever you see it you won't get confused. But some of them are confusing lol.

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Coding to the lowest common denominator of syntax understanding is one reason so much code these days is so bloated and slow. It is not something we should strive towards

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