DEV Community

Cover image for 8 neat Javascript tricks you didn't know in 4 minutes.

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

Blessing Hirwa on December 10, 2020

Introduction Javascript is a powerful programming language especially in web development that is used to create and control dynamic website content...
Collapse
 
lloydfranklinsmith profile image
Lloyd Franklin Smith • Edited

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.

Collapse
 
sureshvv_37 profile image
sureshvv

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.

Collapse
 
lloydfranklinsmith profile image
Lloyd Franklin Smith

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

Thread Thread
 
zackdotcomputer profile image
Zack Sheppard

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.

Thread Thread
 
josefjelinek profile image
Josef Jelinek

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 call Number(s) (not new 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 to 0...

Thread Thread
 
sureshvv_37 profile image
sureshvv

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.

Collapse
 
blessinghirwa profile image
Blessing Hirwa

Yes, it has other alternatives but what's wrong with them please? Is there somethings wrong with the two?

Collapse
 
lloydfranklinsmith profile image
Lloyd Franklin Smith

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.

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

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 😁

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

This makes sense. At this point then one has to be more careful.

Thread Thread
 
jkettmann profile image
Johannes Kettmann

I would disagree. parseInt is much more explicit because it does what it says. It parses an integer.

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

I agree. But all can be used.

Collapse
 
vitalcog profile image
Chad Windham

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 👍

Collapse
 
danielwu profile image
Daniel Wilianto

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.

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

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.

Thread Thread
 
lloydfranklinsmith profile image
Lloyd Franklin Smith

It definitely is good to know and your article did a good job of explaining it.

Collapse
 
destroyer22719 profile image
Nathan Cai • Edited

Hey nice post, however "emptying array" can simply be done with array=[]

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Technically not emptying the array, rather replacing it with a new empty one

Collapse
 
destroyer22719 profile image
Nathan Cai

but it still kinda achieves the exact same thing.

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

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

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

Thanks for the support Nathan.

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

I've never met that kind of error but I'll try it in the future. Thanks for the assistance though.

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

I've never met that kind of error but I'll try it in the future. Thanks for the assistance though.

Thread Thread
 
industral profile image
Alex Ivasyuv

var a = [1, 2, 3]
var b = a;
a = [];
console.log(b); // [1, 2, 3]

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

Collapse
 
eecolor profile image
EECOLOR

I noticed some other people have already voiced their concerns about +string and number + ''. 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 for NaN. Please note the difference in output between these two forms:

+''
parseInt('', 10)
Enter fullscreen mode Exit fullscreen mode

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:

`${value}`
value.toString()
Enter fullscreen mode Exit fullscreen mode

Here I think toString() might be best because it forces you to make a conscious decision on how to deal with null and undefined. When dealing with outputting for display I would probably recommend ${value}.

Collapse
 
gilfewster profile image
Gil Fewster

Good catch on the parseInt('',10) vs +''

But on the flip side, consider:

console.log(+'1,234')  //  NaN
console.log(parseInt( '1,234', 10)) //  1
Enter fullscreen mode Exit fullscreen mode

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.

const stringToNumber = (str) => { 
  // whatever code we use in here, the name
  // of the function clearly indicates our intent
  const num  = +str;
  if (str.length == 0 || isNaN(num)) {
    throw new Error (`Cannot coerce ${str} to Number`);
  }
  return num;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ajinspiro profile image
Info Comment hidden by post author - thread only accessible via permalink
Arun Kumar

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.

 
gilfewster profile image
Gil Fewster • Edited

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.

Collapse
 
eecolor profile image
EECOLOR

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.

Thread Thread
 
gilfewster profile image
Gil Fewster

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.

Collapse
 
blessinghirwa profile image
Blessing Hirwa

I like this one.

Collapse
 
sureshvv_37 profile image
sureshvv

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.

Collapse
 
blessinghirwa profile image
Blessing Hirwa

It was available in Ecmascript 2020

Collapse
 
sureshvv_37 profile image
sureshvv

Short circuiting logical operators have been around for over a decade. I don't think that is new.

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

Some in the comments said that they didn't know it so it was beneficial to some. Btw thanks for the feedback 😊

Collapse
 
blessinghirwa profile image
Blessing Hirwa

And also it was available in Typescript 3.7

Collapse
 
ram12ka4 profile image
Info Comment hidden by post author - thread only accessible via permalink
Ram Kumar Basak

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

Collapse
 
majiyd profile image
majiyd

Can't you people express yourselves without being condescending?

Collapse
 
blessinghirwa profile image
Blessing Hirwa

ohhh I didn't catch that. Thanks the correction.

Collapse
 
themightyt_v3 profile image
theMightiestT

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.

Collapse
 
blessinghirwa profile image
Blessing Hirwa

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 😊

Collapse
 
glowkeeper profile image
Steve Huckle • Edited

But I knew all of them! ;)

Collapse
 
greybax profile image
Aleksandr Filatov

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...

Collapse
 
jeremy_chambers profile image
Jeremy Chambers

I learned something new, thank you!

Collapse
 
pris_stratton profile image
pris stratton

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.

Collapse
 
mitya profile image
Dima

How can i replace this method
.filter((item, index, array) => array.indexOf(skill) === index)
by new Set?

Collapse
 
blessinghirwa profile image
Blessing Hirwa

Do you want to extract unique values from this array?

Collapse
 
mitya profile image
Dima

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', ],
},

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa • Edited

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.

Collapse
 
pl709 profile image
pl709

Nice post with neat tricks

Collapse
 
pozda profile image
Ivan Pozderac

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!

Collapse
 
blessinghirwa profile image
Blessing Hirwa

wow, that's good to hear. Optional chaining really saved me a lot of pain.

Collapse
 
bestverie profile image
Best Verie Iradukunda

tnx a lot

Collapse
 
mdhesari profile image
Mohammad Fazel

thanks

Collapse
 
achinikechider2 profile image
Achinike Chidera

This is beautiful. I saw John Smilga use most of these in his React Course.
Thanks for making it a lot clearer.
Much love! ❤️

Collapse
 
blessinghirwa profile image
Blessing Hirwa

I'm happy to heart that 😁

Collapse
 
adahyto profile image
Adam

Thank You!

Collapse
 
oreste profile image
Oreste Abizera

good content. Loved "Optional Chaining" 😍

Collapse
 
blessinghirwa profile image
Blessing Hirwa

Try it, it really saved me from a headache especially in React lol 😂

Collapse
 
kalashin1 profile image
Kinanee Samson

Wow, i just learnt some nifty new trick. Thanks a lot

Collapse
 
blessinghirwa profile image
Blessing Hirwa

Glad to hear that it was useful 😁.

Collapse
 
didiermunezer38 profile image
Didier Munezero

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.

Collapse
 
blessinghirwa profile image
Blessing Hirwa

I'm glad to hear that you found it useful.

Collapse
 
jrmromao profile image
Joao Romao

Thank you for the post.

Collapse
 
carlosabud profile image
Carlos A.

Thanks for the post.

You may also use String(value) to cast value to string.

Collapse
 
blessinghirwa profile image
Blessing Hirwa

ohhh wow. Thanks :)

Collapse
 
supermari0s profile image
Μάριος

Nice tricks, I would avoid 1& 2 though in a real project 😄

Collapse
 
sureshvv_37 profile image
sureshvv

Calling these as "tricks" is not giving these "techniques" the respect they deserve. :)

Collapse
 
bestverie profile image
Best Verie Iradukunda

Awesome mr. Stack . thanks for sharing

Collapse
 
blessinghirwa profile image
Blessing Hirwa

I'll try to share more of what I know.

Collapse
 
ineam profile image
Amine M

hi, thanks for sharing, just wanna know is there any reason for using snake case ?

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