Introduction
Javascript is a powerful programming language especially in web development that is used to create and control dynamic website content...
Some comments have been hidden by the post's author - find out more
For further actions, you may consider blocking this person and/or reporting abuse
I really dislike 1 and 2 if someone tried to get a pull request passed using those techniques I would reject them.
It just makes the code harder to read because it isn't immediately if you are attempting a conversion or just made a mistake.
Why would you assume that it is a "mistake" when there is a perfectly reasonable alternative?
These are idiomatic usages that will become popular over time. Since code lives forever, economy of expression is vital.
It isn't that I would assume it is a mistake its more that parseInt clearly lets me know it wasn't which prevents misunderstandings at the end of the day this is a code style issue and every team needs to develop their own to work together efficiently for me that means writing my code in a way that won't confuse people less familiar with JS then myself(I'm a freelancer and am often get called in when someones 'in over their heads').
Concerning the economy of expression, we seem to have very different development philosophies I would rather write a few lines more and have my code be either to understand then confront any future developers with clever ternary expressions and one liners.
Code doesn't live forever it is constantly changed and replaced requirements and environments change so it is important we keep things flexible which in my opinion includes preferring code the function of which someone that doesn't even know the specific language could understand.
Sorry about the blog post and lets not forget that the two methods under discussion function differently
I agree with Lloyd here about using the single "+" instead of writing "parseInt". While it's a fun trick to know about, this would also be a thing I would flag (or worse, miss) in a PR and ask to be changed to the more understandable "parseInt".
Economy of expression or terseness isn't more valuable than understandability, otherwise we'd all minify our code before committing it.
parseInt(s)
is not a good example, it works very differently and has a radix issue...parseFloat(s)
is closer, but still ignores any junk at the end of the string... I usually callNumber(s)
(notnew Number(x)
, which has even worse problems), which is explicit and behaves just like unary+
operator... Even this has a surprising issue of an empty string evaluating to0
...Do not confuse Economy of Expression with Minification because the intention of the former is to increase clarity and ease of understanding. Sometimes fewer words express more clearly what is intended and longer sentences are a means of hiding the real crux of the message.
Yes, it has other alternatives but what's wrong with them please? Is there somethings wrong with the two?
It's just unnecessarily difficult to tell what you are trying to do which makes the code less maintainable with parseInt I can look at the line and immediately know you meant to receive a number with the + method you might have wanted a string and just made a mistake and forgot whatever should have come before.
The reason why you see parseInt and know what it's doing is because you're familiar with it, so by the time many people become familiar with it then they'll easily recognize it, but I think this ones are also obvious by the way. But anyway it's totally fine, thank you for the feedback π
This makes sense. At this point then one has to be more careful.
I would disagree. parseInt is much more explicit because it does what it says. It parses an integer.
I agree. But all can be used.
When using the parseInt or toString methods, it is an example of self documenting code. The instructions of what is happening are in the methods themselves, like writing comments without having to write comments. Simple, straightforward, self-documenting code is the best type of code when working large production code bases IRL. Your tricks were fun though, thanks for sharing π
parseInt makes it obvious that we want to get an integer (from string). Using +"123" is confusing, and it's not apparent that we want to get integer 123. There is a reason why programming languages use natural language.
yes but there's always a reason why something was invented. Sometimes you'll see where people used these kind of tricks so it's good to know them too.
It definitely is good to know and your article did a good job of explaining it.
Hey nice post, however "emptying array" can simply be done with
array=[]
Technically not emptying the array, rather replacing it with a new empty one
but it still kinda achieves the exact same thing.
Not really. If you have another reference to the original array, and you use this method to 'empty' it - stuff is going to break as the other reference will still contain the unemptied array
Thanks for the support Nathan.
I've never met that kind of error but I'll try it in the future. Thanks for the assistance though.
I've never met that kind of error but I'll try it in the future. Thanks for the assistance though.
var a = [1, 2, 3]
var b = a;
a = [];
console.log(b); // [1, 2, 3]
I noticed some other people have already voiced their concerns about
+string
andnumber + ''
. I would like to raise some concerns myself.As you mentioned in one of the comments, in real life it would be
+someVariable
. This means that the value most likely is from an external source and should be checked forNaN
. Please note the difference in output between these two forms:Another reason I would prefer
parseInt
is that it is now clear the value was supposed to be parsed as an integer and there is no typeo.For
a + ''
my only argument is the intention one. To me it's much more clear if it is written as follows:Here I think
toString()
might be best because it forces you to make a conscious decision on how to deal withnull
andundefined
. When dealing with outputting for display I would probably recommend${value}
.Good catch on the
parseInt('',10)
vs+''
But on the flip side, consider:
In this instance, I'd say the unary operator gives a more reliable result, since NaN at least indicates an error in type coercion. The result from parseInt is not correct, but is still a valid number so a much more difficult bug to catch.
Either way, the moral of the story is that almost any method of type coercion is vulnerable to failure unless the data is carefully sanitised beforehand.
As far as which method best indicates the intended operation, I think the solution most often is to wrap the code inside a function, so that the intention is signposted by the function name not the implementation code.
Ahh yeah, I forgot about the fact that
parseInt
ignores anything non-numeric after a number.I would still rather use
Number(value)
to+value
to clarify intent.Yeah, I donβt think Iβd use unary plus either, but sometimes a use case presents itself for unexpected things. I certainly didnβt know about it, and now I do, so Iβve learned something.
I think partly the dislike of it comes from its unfamiliarity. We donβt see it in common use very often, whereas the old value * 1 trick for type coercion is scattered throughout the internet. While you could certainly debate the wisdom of that technique, Iβd imagine most developers would understand the intent immediately when they see it β largely because itβs an old and well-known shortcut. But on the face of it, multiplying something by 1 could seem a pretty pointless thing to do.
This is all a great example of the fact that what we think of as intuitive as often really just what we learned through repetition and convention.
Great one, Gil. I truly appreciate your js skills. But the author hasn't mentioned this in his post, has he ? He is simply promoting the use of unary operator for string conversion instead of using parseInt( ), FOR WHICH he is receiving EECOLOR's criticism (and mine for that matter).
Even though I accept your point that in the case you mentioned above, where use of unary + is better than parseInt - I strongly disagree this is a real world scenario. We explicitly make a string variable to number only when we actually know it is going to be a number. If a developer would knew there is going to be a comma between the numbers they would be replacing those commas with nothing, which will produce correct results.
I agree that relying on the coercion method alone is dangerous and liable to produce errors.
Which is why I said in my previous post that almost any method of type coercion is vulnerable to failure unless the data is carefully sanitised beforehand.
I like this one.
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
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!
How would that be a win?
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,
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:
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.
That's a good example Gil. Thanks π
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
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.
Since what version of javascript these features are available?
My sense is that the shortcut logical operators have been there forever (inspired from C) whereas the null coalescing operators are fairly recent.
It was available in Ecmascript 2020
Short circuiting logical operators have been around for over a decade. I don't think that is new.
Some in the comments said that they didn't know it so it was beneficial to some. Btw thanks for the feedback π
And also it was available in Typescript 3.7
There is a below silly mistake
let replace_string = "Visit stunnitysoft. stunnitysoft is a software company";
console.log(replace_string.replace(/stunnity/, "Micros"));
It prints Visit Microssoft. stunnitysoft is a software company
Can't you people express yourselves without being condescending?
ohhh I didn't catch that. Thanks the correction.
that first example of string conversion is actually implicit type coercion - not really a "neat trick" but an oft-debated "feature or bug" point of contention.
also really bad practice.
I've been using it for a while but I've never met a problem with it, but I'll inspect that too. Thank you for the feedback π
great set of snippets! Didn't know some of them. I have list of js snippets as well just check it out in my blog alfilatov.com/posts/useful-js-snip...
I learned something new, thank you!
I didnβt know you could add a β+β before a string to turn into a number. Iβm not sure I particularly like it, either. Iβd prefer to see Number(string) which feels clearer.
But I knew all of them! ;)
How can i replace this method
.filter((item, index, array) => array.indexOf(skill) === index)
by new Set?
Do you want to extract unique values from this array?
From some object with array inside. Like this (array with fruits):
const elements = [
{
type: 'Product',
email: 'buy@buy.com',
isTasty: true,
fruits: ['kiwi', 'mango', 'banana', 'kiwi', 'banana', 'orange', ],
},
Try this:
elements.map((element) => {
let unique_values = [...new Set(element.fruits )]
// console.log(element.fruits)
return unique_values;
})
or simply do it like this:
console.log(elements.map((element) =>
unique_values = [...new Set(element.fruits )]
))
You can either console them or store them in a variable. Overwriting the old values is also possible.
Thanks on this great article,
I am already using them for years now (optional chaining was available in babel) them except 1. and 2. and array shorting/emptying as I never really had need for those!
wow, that's good to hear. Optional chaining really saved me a lot of pain.
thanks
Thank You!
Nice post with neat tricks
Cool from our brother.
For sure I did not know all the tricks above.
Well some can be done in other simple ways but
Thank you a lot.
I'm glad to hear that you found it useful.
This is beautiful. I saw John Smilga use most of these in his React Course.
Thanks for making it a lot clearer.
Much love! β€οΈ
I'm happy to heart that π
tnx a lot
Wow, i just learnt some nifty new trick. Thanks a lot
Glad to hear that it was useful π.
good content. Loved "Optional Chaining" π
Try it, it really saved me from a headache especially in React lol π
Nice tricks, I would avoid 1& 2 though in a real project π
Calling these as "tricks" is not giving these "techniques" the respect they deserve. :)
hi, thanks for sharing, just wanna know is there any reason for using snake case ?
Thanks for the post.
You may also use String(value) to cast value to string.
ohhh wow. Thanks :)
Thank you for the post.
Awesome mr. Stack . thanks for sharing
I'll try to share more of what I know.