Skip to content Skip to sidebar Skip to footer

Method Vs Basic Js? Should I Use Tostring? Parseint? Jquery?

This is a question I've been wondering about ever since I found the toString() function, but have never bothered to ask. Should I use basic JS or the function that does the same th

Solution 1:

Not only is this shorter, but according to JSPerf the toString method is 97% slower!

Unless you're calling .toString() on hundreds of millions of numbers every second and you've found that this is a bottleneck in your application through profiling, this should not be a factor at all.

But admit it: we mainly use toString for converting numbers to strings

As you've seen, this can be done implicitly by just adding a string and a number together, so I fail to see any benefit of using '' + n in place of n.toString(). The latter is more readable when you're not actually concatenating n with a string.

However, multiplying is shorter, will work in any browser, and parseInt, remember, will only return integers.

Are you saying that parseInt doesn't work in every browser? If you want to parse something as an integer, use parseInt. If you want to parse something as a float (JavaScript doesn't actually have a special type for either, all numbers are floats), use parseFloat.

The more common pattern is using +'123', which has the exact same behavior as 1 * '123'. parseInt handles empty strings properly, but for whatever reason does not validate strings as you'd expect. The unary plus returns NaN in case of an error, but treats whitespace and empty strings incorrectly. It's one of JavaScript's shortcomings, so there's really no concrete choice between the two if you're working in base 10.

So why does it always come up as the answer to questions, asking how to convert to numbers/what NaN is?

Because the spec included these functions to convert strings into numbers and converting strings into numbers using binary operators like you're doing is a side effect, not the primary purpose. Also you can parse integers in different bases using parseInt, which isn't possible with type coercion.

It may simplify certain functions and stuff, but why not just copy those functions to your page then and leave out the remaining functions you don't use?

If you load jQuery from a CDN, then there's a really good chance that a user's browser has already downloaded it and has it cached, making download times and bloat almost nonexistent. If you make a "custom build", I'd bet that it'll make the site slower on first load.

And animation isn't excused either here - because that too can be done with native Javascript.

So can everything. There's no point in reinventing the wheel every time you write something.

Post a Comment for "Method Vs Basic Js? Should I Use Tostring? Parseint? Jquery?"