DEV Community

Cover image for 10 Practical JavaScript Tricks

10 Practical JavaScript Tricks

Zander Shirley on April 30, 2020

I'm always on the lookout for new ways to be more efficient. And JavaScript is always full of pleasant surprises. 1. Transform the argum...
Collapse
 
david profile image
David Hunt

Eh, I hate to be a jerk, but this is full of really poor practices. To be honest, I stopped after 2 or 3 because they're teaching bad lessons.

Examples:

  1. arguments should be deprecated in favor of rest parameters.
  2. Your reduce function is missing a starting value, a 0 in this case as the second argument to reduce.
  3. Mutating function arguments.
  4. (and others) relying on side effects of ECMAScript APIs instead of using reliable APIs.

Please, beginners reading through this, don't do most of these things.

Collapse
 
zandershirley profile image
Zander Shirley

I appreciate that you took the time to write a comment.

You remind me of a friend that has been waiting for 2 years to get some experience in order to give advice to beginners.

He just keeps giving strange advice and the junior devs simply ignore him.

  1. arguments is not deprecated.

The MDN webdocs just provide the following note:
If you're writing ES6 compatible code, then rest parameters should be preferred.

I never said that you should write all of your code with the tricks that I used, they're just presented as an interesting read.

It seems you just missed the point completely.

Collapse
 
dmalechek profile image
dmalechek

Nice tips for any of those contests to do things in the few number of lines, but I'm with David Hunt, this is almost a must set of error lint rules. In enterprise apps, never sacrifice readability for fewer lines of code without a very, very good reason.

If you don't like his comments, I might say why did the world need another "10 javascript..." repeat article?

Collapse
 
ikoshelev profile image
IKoshelev

"You remind me of a friend that has been waiting for 2 years to get some experience in order to give advice to beginners."

Your friend is right. When I see advice like the ones in the article, I usually say "I hope your doctor and your lawyer are better at their job than this."

I've handled over a 100 front-end interviews for my employers and code like that would seriously hurt candidates chances.

Thread Thread
 
zandershirley profile image
Zander Shirley

It's pretty obvious that these tricks do not make your JavaScript more readable, they're not supposed to help with readability.

The purpose is to show the reader that things in JavaScript can also work this way.

I'm sure you're an expert in the bleeding edge technology that your employer is using and you're really good at those interviews, but it seems you just missed the point of this article.

Thread Thread
 
ikoshelev profile image
IKoshelev • Edited

merriam-webster.com/dictionary/pra...
Practical:

  • "of, relating to, or manifested in practice or action : not theoretical or ideal"
  • " capable of being put to use or account"

"The purpose is to show the reader that things in JavaScript can also work this way." - even you yourself describe this precisely as theoretical. Practical is "here is how this should be done".

Look, I would not be commenting here, if I haven't seen over and over again junior devs reading such articles and rushing to use tricks from them everywhere. The best course of action for you would be to remove half of the tricks you've written, since only harm can come out of them. The question is - are you willing to admit you were wrong or is your ego more important to you than your readers?

Collapse
 
czescwojtek profile image
Czesc Wojtek

Enough already! I can't stand this very kind of pseudo-articles. Just keep your knowledge to yourself until you have something that is actually worth posting and is in some way innovative. DEVto and Medium are nowadays full of totally worthless posts made just to get the attention, not the knowledge. I mean what is this? Attention seeking? A boast?

Collapse
 
evankapantais profile image
Evan Kapantais

Plus, at this point, all there is to read here is top-10 lists. This is not Youtube.

Collapse
 
bdougherty profile image
Brad Dougherty

Agreed with some other comments that there are quite a few issues here.

1- Better to use the standardized Array.from() which is designed for use with array-like objects such as arguments. Better yet, rest parameters should be used when possible, since they are more explicit than arguments.

3- Perfectly valid syntax, but using the if is much more clear and explicit about the intention.

4- Using default parameters is not only more explicit, but it also avoids issues when you want a falsy value to be possible (the code in the article will not allow 0 for example, but that might be completely valid)

function doSomething(arg1 = 32) {
    // … do something here
}

5- Not sure there is actually a practical application of this. I sound like a broken record at this point, but since most people do not know this, it makes the code much more difficult to read. Always be explicit.

6- array.slice() is more clear about the intentions.

10- This is a great one. I use it

Being responsible is far more important than being efficient.

That closing thought is extremely important, unfortunately most of the tricks here are ultimately not responsible.

Collapse
 
ikoshelev profile image
IKoshelev • Edited

Sorry to point this out, but about half of this advice are bad.

3 hungry && goToFridge() - no. Your code is written once and then read 10 times. This makes it harder to read.

4 And now you can't have 0... Use default args.

function doSomething(arg1 = 32){ 
//....
}

If you are dealing with variables - use nullish coalescing operator.

a = a ?? 32;

5 'Coma operator' - don't use it as described ever. It is a constant source of bugs.

6 'Using length to resize an array' - try avoiding this. It is a hack that hides intentions and leads to bugs.

P.S.
1

const args = Array.from(arguments); // just make sure to polyfil if you expect older browsers
Collapse
 
wangqiyang profile image
wang-qiyang

Hi Zander

I am the editor of InfoQ China which focuses on software development. We like your article and plan to translate this into Chinese.

Before we translate and publish it on our website, I want to ask for your permission first! This translation version is provided for informational purposes only, and will not be used for any commercial purpose.

In exchange, we will put the English title and link at the end of Chinese article. If our readers want to read more about this, he/she can click back to your article.

Thanks a lot, hope to get your help. Any more question, please let me know.

Collapse
 
zandershirley profile image
Zander Shirley

Hi,
Yes, you have my permission to do that.
Thank you for asking.
Please don't remove any part from the article when you translate it.

Collapse
 
wangqiyang profile image
wang-qiyang

infoq.cn/article/fgeB0Bu3jpAzmba9ro3x
any questions pls let me know, thx

Collapse
 
wangqiyang profile image
wang-qiyang

Sure, thx a lot, will post our translation link here after we publish it.

Collapse
 
avraammavridis profile image
Avraam Mavridis
  1. I would just use Array.from(arguments) but still can't see a real scenario that you would need to use array functions in the arguments list

  2. Here your function will fail if the passed value is 0.

function doSomething(arg1){ 
    arg1 = arg1 || 32; // if it's not already set, arg1 will have 32 as a default value
}
Collapse
 
rafibomb profile image
Rafi

Love seeing the "weird" parts of JavaScript. Can you elaborate on the Shuffle, where the '- 0.5' comes from?

Collapse
 
activenode profile image
David Lorenz

The sort function sorts before/after by checking negative vs positive numbers (0 means equal). Since random gives back anything between 0 to 1 you would never have a negative number. So you just simply substract -0.5 .

Collapse
 
zachlitz profile image
Zach • Edited

I think this is wrong though?
Since random is exclusive of 1, you're going to be slightly biased towards negatives, and thus not totally uniform (assuming that's the goal which 0.5 implies), right?

Maybe it should be Math.floor(Math.random() + 1) - 0.5
I think...

Thread Thread
 
activenode profile image
David Lorenz

Your proposed code always returns 0.5 since you floor a number x with 1 <= x < 2 which floored always gives 1 and therefore 1 - 0.5 = 0.5 so I do not think your solution would lead to anything useful in this case since it would not shuffle at all :)

The JS spec says:

Returns a number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly or
pseudorandomly with approximately uniform distribution over that range, using an implementation-dependent
algorithm or strategy. This function takes no arguments.

That means we can trust the uniformity of it EXCLUDING the exact number 1 but including 0. So your argument is that we miss out on non-uniformity because it can only reach 0.99999999999999999 but in fact from a mathematical perspective this is the same number as 1. Not just mathematically but also in fact 0.99999999999999999 == 1 in JavaScript. Even if it was not (just theoretically) then the missing bit would be so extremely small that it would essentially become insignificant.

Thread Thread
 
zachlitz profile image
Zach

Oops, I should have said Math.floor(Math.random() * 2)

But I'm still not convinced of your argument. I agree that it is most likely insignificant, (considering the PRNG is essentially a black box and I don't even know if it is a standard implementation across all engines, and if it is it probably is not uniform to begin with). Add to the fact that we are dealing with FP and not continues numbers also muddies the water. But all else being equal, we would have a bias because the random function is not inclusive. But then again on a second though, the sort function would also return the same for 0.5 as it would for 0.5 + ε so that effectively gives you a uniform range of values.

For what it's worth, I tried running it in V8 (billions of times) but couldn't discern any patterns either way (but I was just seeing if the average was above or below 0 and logging the output; it would be interesting to investigate it further with proper statistical analysis.)

Thread Thread
 
activenode profile image
David Lorenz • Edited

Hey Zach. Maybe if you "mistrust" it then you rather first read the JS specs. The Engines are not allowed to interpret the distribution differently since they are spec based.

Your arguments are, sorry to say, invalid since the uniformity for the random function is given and due the to equalness of 0.99999999999999999 == 1 and the INEQUALNESS of 0.00000000000000001 == 0 . So there is your missing bit. Your so-called Epsilon does not exist since this is there is no more Epsilon than this. I just wrote the minimum and maximum numbers the Math.random returns.

Also again you probably meant with your example Math.floor(Math.random() * 2) - 1 since you are trying to have a "real" integer 1 inclusion but this does not change anything since from a mathematical perspective the distribution does not change with a factor for this sample since the factor is strictly linear.

Also if you have a "general" mistrust in the Math.random function then this is totally fine because it is "not really" random. There is the WebCrypto API which tries to provide way better randomized values.

Collapse
 
activenode profile image
David Lorenz

Array.prototype.slice.call is very much a workaround for just calling Array.from if you'd really like to do it explicitly instead of using the ... operator.

Collapse
 
val_baca profile image
Valentin Baca

That shuffle function is great!

Collapse
 
ieeebruce profile image
ieeebruce

thanks for your tips NO.9, I never know it before

Collapse
 
charles66982918 profile image
charles hollins

I think the best way to practice javascript is -

  1. You need quality content or a book for that to study javascript.
  2. Read basics carefully because basics are the building blog to practice javascript.
  3. Try to use study material in javascript coding and try to prepare a scenario-based project.
  4. Up to date about javascript read blogs about that.
  5. Manage senior person javascript-based project and try to understand that project.
  6. For advance label try the git hub project and try to contribute to the opensource project.
  7. The last thing that needs the practice to solve the problem, algorithm.
Collapse
 
fkereki profile image
Federico Kereki

Hi! The shuffle() code isn't really a very good shuffle, insofar that not all possible permutations are equally probable. I'd rather read en.wikipedia.org/wiki/Fisher-Yates... for good algorithms.

Collapse
 
alvechy profile image
Alexander Vechy

@zandershirley , take all the critique like if you expected to get it when you published. We learn in public in order for other people, more experienced, to come and say what's wrong with the things we wrote. I love the web for it, there is always someone smarter in some field. No one says you're a bad developer, they just aware you that there are many novices who read the article and decide to use the tricks in their day to day jobs "because they can". Which is not good, as explained in the comments.

Collapse
 
bobj2018 profile image
Joshua Rieth

To provide a default parameter value:

function doSomething(args1 = 31) {

}

If an argument is passed, it is used rather than the default.

Collapse
 
arupkumarbehera profile image
Arup kumar Behera • Edited

Awesome article where I could get informed about old/new tricks.
Tip no. 4 : The problem there is if arg1 is 0 and 0 is a defined valid value. What do you think ?

Collapse
 
darkpsy profile image
The Spirit Molecule

A moment of silence for people functional programming aficionados who died at 6 😂(Myself included)

Collapse
 
jappe999 profile image
jappe999

Nice list! Only I wouldn't recommend trick number 3, because it's not that readable and can confuse your team members (or your future self).

Welcome to DEV.to by the way!

Collapse
 
dsibinski profile image
Dawid Sibiński

"3. Short circuit conditionals."
I use this one especially in React for conditionally rendering or not some components 😉
Short, nicely-written and useful article - thanks!

Collapse
 
ayushkushwah profile image
Ayush Kushwah

6 - DON'T MUTATE PROPERTIES WHICH ARE SUPPOSED TO BE READ-ONLY LIKE THIS.
This is why methods are invented to play on objects (like slice or splice).
This the most amateur thing I ever read.