DEV Community

loading...

JavaScript/Typescript Tips compilation 2021🚀

KR Tirtho
A boy with million dreams.
Updated on ・3 min read

I'll be discussing the newest JavaScript/Typescript tips which also includes ES2020 additions & Typescript's new type related additions in this post

Optional Function Call

There are often time you wanna callback a function inside a function. The callback function is most of the time optional. So you've to check whether its defined or not to avoid <function name> is not callable kind of errors. This is where optional function call comes to play

picture of using optional function call instead of checking the function is defined or not manually

_ separator for unreadable numbers

Often times bigger numbers create readability problems. At this situations you can use _ to separate numbers
picture of using _ separated numbers instead of using big numbers directly

Use Array.entries to get the index in for_of loop

JavaScript's for_of loop is awesome. Its much readable than ugly forEach higher order function. But many times we need the index of the current element. Which is not provided by default in for_of loop. There Array.entries comes to play. It converts array of elements to array of index, elements

But this readability puts performance at stake. As Array.entries has to take an extra iteration to map out the index. So you can expect it 20-30% slower than regular forEach/for loop. Thanks to @lukeshiru for the correction❤️

usage of Array.entries method

[Typescript] template literal types

Its hard to do string validation in JavaScript/Typescript. Checking each type of string combination is hard. In Typescript union | helped but its repetitive. So template literal types were introduced
picture of template literal types usage

[Typescript] override keyword

Overriding parent class methods aren't new thing. This is available in all OOP language. But in JS, you can do anything, sometimes unwillingly. But Typescript 4.3 beta introduced override keyword for making method overriding safer. You've to use override keyword before the method name you're willing to override
You've to set noImplicitOverride true in tsconfig.json to make this feature work
picture showing how to use the override keyword

+ operator as an alternative to parseInt & parseFloat

Know about parseInt or parseFloat method for parsing numeric string, right?
You can also use the + operator in front of any numeric string to parse it as a number
It will return NaN if the string isn't numeric

Its not recommended to replace parseInt or parseFloat. As this can cause unknown bugs & behaviors as + is an arithmetic operator too & it converts empty string "" to 0 which is not good. So don't use it always. It also harms the readability. Mentioned it as its a doable thing too.... Again thanks to @lukeshiru for pointing out the problems❤️

image showing how + operator can be used as an alternative to parseInt & parseFloat

[Typescript] Type shadowing⚡💪🏻

May be your function accepts multiple types of arguments & parses/validates them safely & returns different types/shapes of result based of the arguments passed. In this case type shadowing comes handy. You can declare same function multiple times with different sets & types of arguments with desired outcome. Type shadowing works for other types too

picture showing how type shadowing works

Discussion (28)

Collapse
lukeshiru profile image
LUKESHIRU • Edited

I've seen the + instead of parseInt/parseFloat in a few posts already, and I couldn't disagree more. Is better to use parseInt and parseFloat to be clear about the intention of your code. Also, the Array.prototype.entries tip, you should just use Array.prototype.forEach or Array.prototype.map instead:

moods.forEach((mood, index) => console.log(`${index}. ${mood}`));
// or
moods.map((mood, index) => console.log(`${index}. ${mood}`));
Enter fullscreen mode Exit fullscreen mode

This is also faster than your entries approach.

Cheers!

Collapse
nombrekeff profile image
Keff • Edited

I agree with the +, it should not be used that often, if ever.

But, it's not always about speed, I think he was just showing other less common methods, that are useful in some scenarios. Though I have tested and It's quite a lot slower, around 27%. Benchmark here

Though this post was not about performance, I think it's always good to advise people.

Collapse
lukeshiru profile image
LUKESHIRU

I generally don't care much about performance, but I personally don't see much benefit in using Array.prototipe.entries mixed with for, when you can either just use a regular for, or just use a method to loop trough the array like map or forEach.

Thread Thread
nombrekeff profile image
Keff

That's true, I can agree with that. The example was a weird use-case, but entries has some uses though.

Funny, on my test benchmark I realized that a regular for is slower than forEach in that particular example, wich surprised me a bit. I'm guessing the engine is doing some optimization, which are not done for regular fors...

Thread Thread
lukeshiru profile image
LUKESHIRU

Yup! Both map and forEach have some optimizations at the engine level ☺️

Collapse
gruckion profile image
Stephen Rayner

You mean advise* people. Thank you dot the feedback

Collapse
krtirtho profile image
KR Tirtho Author

I've updated the post to point out the potential problems that can occur for using + instead of parseInt/parseFloat. Also mentioned the performance penalty for for_of loop with Array.entries so that everyone stays informed...

Thanks to all of you, who've corrected this out. You guys rock💪

Collapse
krtirtho profile image
KR Tirtho Author

Yeah, I saw the difference. for_of is almost 20%-30% slower than forEach. It makes sense as Array.entries has to take an iteration to map out the index. I wonder why there's no native way of getting the index in for_of without a performance penalty🤔! for_of is so much more readable & mitigates the callback hell at least a little bit

Also I wouldn't really recommend anyone to use + instead of perseInt or parseFloat. Just mentioned as it is also doable too

Thank you so much for your corrections❤️

Collapse
jamesthomson profile image
James Thomson

If you wanted an index to reference, but want to use for...of you'd be better off (performance wise) using a variable to track it.

const array1 = ['a', 'b', 'c'];
let i = 0;
for (const element of array1) {
  console.log(element,i);
  i++;
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
lukeshiru profile image
LUKESHIRU

Yup ... or just a regular for, without the of. I believe it has an even better performance.

Not a huge difference, but still. Thanks to this post I broke my year and a half streak of not using for 🤣 ... I never find the need to use a for, having such greatly optimized and idiomatic methods in arrays already ✨

Thread Thread
jamesthomson profile image
James Thomson

For sure! Not much point in using for...of in this use case when a for will do just fine, but I'd also never do a for...of with arr.entries() so there's that too 😂

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
LUKESHIRU • Edited

"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

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
LUKESHIRU • Edited

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

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

Collapse
sesay profile image
sesay

not sure, why i would do this

```const moods = ['good', 'better', 'best']

for ([idx, mood] of moods.entries()) {
console.log(${index}. ${mood})
}```

In my opinion looks a little bit more complicated

Collapse
mistval profile image
Randall • Edited

I agree, + to convert something to a number is a hack. It also converts empty string to 0, which can lead to bugs. Better to use Number.parseInt() (or parseFloat) and then do a NaN check.

Collapse
gruckion profile image
Stephen Rayner

Cheers, I agree

Collapse
dhatguy profile image
Joseph Odunsi

That optional function call. Thank you

Collapse
krtirtho profile image
KR Tirtho Author

Ah, that one really made me amazed when I found it accidentally while optionally chaining objects where one of the property was actually a method😅

Collapse
bglamadrid profile image
Benjamin La Madrid

Optional function calls? Damn, JS/TS is lookin' good, fellas! The more of this comes up, the more I love its syntax!

Collapse
demeno profile image
Demeno

It always bothered me that the override keyword wasn't required, I'm definitely adding this noImplicitOverride: true setting to our project now that I know it exists.

Collapse
captainyossarian profile image
yossarian

Type shadowing is a function overloading

Collapse
talr98 profile image
TalR98

Very helpful, thanks

Collapse
krtirtho profile image
KR Tirtho Author

You're most welcome

Collapse
64467904macias profile image
Juan macias

Vlogmo.com has the cheapest courses

Collapse
joshuapozos profile image
Joshua Pozos

ty