This article collects some common javascript techniques for clean code and better development efficiency
1. Converting string...
For further actions, you may consider blocking this person and/or reporting abuse
One interesting point in these cases of usefull techniques are two things:
Points to the first example:
There are good reasons why we use String() or .toString(). In these cases it is clear that the variable is changing its type. This is not so clear in
""+num
.From a reading point of view you are mixing two types, but you are not transforming it. In the end the JavaScript engine decides for you what it should become, and not you.
It also does not help others to figure out what that shortcut really does and could ask why you add an empty string to a number (if you read it literary) just to transform a number rather use optimised functions for transformation. I would like to ignore template literals in this case, as they have another use case.
What about performance?
You could also look up some benchmarks: measurethat.net/Benchmarks/Show/24...
There are even more benchmarks for this kind of tricks.
I don't say you should always use the best thing for performance, but using some weirdness of a language just because you can might hurt the readability and in the end maintainability.
Else, a nice read. Thanks and keep going 😃
Hi damian, thanks for the comment and putting the point on readability and performance. I have only pointed out some useful techniques which means we can also use them if we like to use. Im not saying it is best for performance. Infact, i mostly use String() and template string in my codes as well. Thanks again!!
Readability is completely subjective, and preaching it above all else can damage the quality of developers over time - sweeping features or 'weirdness' of a language under the carpet will only result in a diminishing understanding of that language and the various 'tricks' (for performance, brevity etc.) that are available.
Learn everything you can about a language and make your own decisions about what features are best to use in each situation. Don't bow to dogma.
Agreed. Thanks for the comment Jon!!
To convert numbers to strings, you can also use string templates:
This is a far more readable way to do it
There are few other methods as well. But template string is the one i mostly use as well. Thanks for reading!!
In the second example shouldn't the names be like this?
const num = 123;
const str = ""+num
My bad.It should be like this, i'll update. Thanks!!
In my opinion, first and second points looks so dirty
Might be, but these are only useful Techniques. So we need to use as per our case. Thanks for reading!!
useful
Thanks nikesh. I hope you liked it. Happy reading!!
Only 1 (I think) item here has anything to do with ES6