DEV Community

Discussion on: JavaScript/Typescript Tips compilation 2021🚀

Collapse
zulvkr profile image
zulvkr

A counter argument.

I feel + for number conversion is extremely common in JS and readable. The behavior meets expectation well, it can be float or integer when I don't care.

It looks intentful, since everyone know JS type coercion.

I will give code a pass.

Collapse
lukeshiru profile image
Luke Shiru • Edited on

"plus variable" is not as readable as "parseInt variable" or "parseFloat variable". Sorry, but it isn't. You're just using the automatic coercion, which is hacky for sure. The same applies to stuff like short-circuiting. It doesn't have any benefit other than looking "smart". I can only imagine how a line of code adding 2 ints that you had to parse would look like, and ... oh my ...

const total = (+value1) + (+value2); // ???
Enter fullscreen mode Exit fullscreen mode
Thread Thread
zulvkr profile image
zulvkr • Edited on

Yeah, that one isn't. But outside arithmetic it's ok.

It just need common sense to know mixing + and arithmetic is bad. Well, lots of people has no common sense, haha.

Thread Thread
lukeshiru profile image
Luke Shiru • Edited on

They mentioned it in other comment, but you also have this little problem:

+""; // 0
parseInt("", 10); // NaN
Enter fullscreen mode Exit fullscreen mode

And I can add stuff like:

+"1e3"; // 1000
parseInt("1e3", 10); // 1
Enter fullscreen mode Exit fullscreen mode

This kind of things happen a lot with "hacky" code. It is shorter yes, and it looks smarter, but is "harder to read" (intention is not as clear as it should), and is more error prone.

Thread Thread
zulvkr profile image
zulvkr • Edited on

I'm still on the edge of converting to parseInt parseFloat sect. But their behavior to convert '23 somestring' to 23 still off putting to me.

Looks like a possible silent failure for edge cases

Edit: I found an actual case, bennadel.com/blog/3803-i-prefer-th...

I am not saying + is better overall, but it has better behavior in this case