DEV Community

14 tips to write better Javascript

Melvinvmegen on December 12, 2023

Here are some of my favorite tips for writing cleaner Javascript code, skip the clever keep it simple. 1. Forget about var Declare al...
Collapse
 
ademagic profile image
Miko • Edited

All good advice but I think a lot of these are standard ways of working in modern JS. I looked back at some of these and forgot you could do it the wrong way. JS has come a long way in that respect.

But a timeless and massively underrated tip

14. Readable code outshines clever code

Every language. Every time.
Thanks for the article!

Collapse
 
melvinvmegen profile image
Melvinvmegen

Yeah, you're right! But not all JS code has been written after ES6, unfortunately, and on a day-to-day basis, I still encounter a lot of legacy code that deserves to be refactored. I personally use those rules as a reminder :)

Collapse
 
ademagic profile image
Miko

Great point, I only thought about this as how to write new JS, I didn't even consider this article from the refactor perspective. Hopefully a lot of this gets picked up by linters, its always nice when automation helps you write better code.

Thread Thread
 
melvinvmegen profile image
Melvinvmegen

That's true nowadays a well configured linter can catch a lot of it! But still good to know why it matters

Collapse
 
codingjlu profile image
codingjlu

For number 6 the semicolon isn't used for line termination—it's the standard for-loop syntax. Aside from that, generally ASI works perfectly, and if you know its quirks there is nothing wrong with omitting semicolons and can make your code a lot cleaner.

Collapse
 
melvinvmegen profile image
Melvinvmegen

Well if there is a need for ASI it does mean that it's used for line termination doesn't it?
I believe it is a matter of personal preference but to me it just makes sense to be explicit about where the command should end.

Collapse
 
devncoffee profile image
Dev N Coffee • Edited

@melvinvmegen DUDE, DON'T DITCH VAR!

It is very misleading to beginners, and they will never grasp the concept of scope properly.

Otherwise, I will agree with many of the above points, and add on with a couple of the modern operators:

  • Arrow functions
  • Spread
  • Ternary operator
// ARROW FUNCTION
var fn = (name, email) => {
  console.log(name, email);
};

// DUMMY DATA
var person = ["Jon", "jon@doe.com"];

// SPREAD
fn(...person);

// ARROW FUNCTIONS CAN BE "MINIFIED" IF ONLY 1 PARAM AND/OR SINGLE LINE
var double = (a) => { return a *2; };
var double = a => a *2;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
melvinvmegen profile image
Melvinvmegen

Thanks for your additional tips it may help others!

Honestly i think that it's even more misleading when you're learning about scopes that some variables are acting differently than others..

Collapse
 
amiceli profile image
amiceli

I love the 7 rules <3, it makes code easier to read.
I use it since I read Clean Code book.
But the 6 rule ^^ No semicolons for me !

Good posts ;)

Collapse
 
welshapple profile image
William • Edited

Agreed really good post but the part on semicolons is quite funny because half these examples don't even have semicolon line terminations in them.

Should be a matter of preference if you have semicolons at the end of your lines in JS. Personally I don't use them as I think it looks cleaner.

Collapse
 
melvinvmegen profile image
Melvinvmegen • Edited

Thank you! Haha yes indeed even most my examples don't include them, i must say prettier takes care of that for me most of the time.

But indeed it's a matter of personal preference, until you need it!

Collapse
 
melvinvmegen profile image
Melvinvmegen

Thank you for kind words! I feel like semicolons are (or used to be) a big debate in the js world but it as almost no impact so we should probably leave as a matter of personal preference. :)

Collapse
 
carloshdevbr profile image
KaleoSix

One strategy that I like to use is not necessarily in js but in ts, which would be to pass the parameters as typed objects, making TS tell me exactly what it expects to receive in my functions, not only the type it expects to receive, for me I feel that it is much more readable and easier to understand what the function wants to receive

Here's an example

`interface CreateFormDataProps {
key: string;
file: File;
fileName: string;
}

export const CreateFormData = ({ key = 'file', file, fileName }: CreateFormDataProps): FormData => {
const formData = new FormData();

formData.append(key, file, fileName);

return formData;
};
`

Collapse
 
melvinvmegen profile image
Melvinvmegen • Edited

You're right TS is a gem for thoses cases! I could have added TS has a rule but i wanted to focus on JS and i also believe that the bloat that it brings is not always valuable depending on the project size and "importance".

I recently tried jsDoc and i must say it brings even more bloat (as the syntax is not optimal) but i don't have the feeling that i'm writing twice as much code with additional complexity. It just brings types safety thanks to the editor and i'm not forced to use any whenever i'm stuck with a pattern that only a TS wizard would type correctly.

But again maybe it's just that i'm not qualified enough in TS.

Collapse
 
tusharshahi profile image
TusharShahi

Nice post.

A tip for the 3rd rule:
Use const stringObject = String("Charly"); instead and it would create a primitive instead of an object.

Collapse
 
melvinvmegen profile image
Melvinvmegen

Oh that's interesting i didn't know that! But i have to say i'd still use the classic const string = "Charly"

Collapse
 
jackfan profile image
Jack Fan

I think a 'let' should be added in the thirteenth suggestion.

// ✅ Do this
for(let user of users) {
console.log(users);
}

Collapse
 
madeofclay profile image
Adam

Oh man! I thought you were going to catch it too. @melvinvmegen, shouldn't the console log be logging user instead of users? You'll log the entire array the number of times of the array's length 😅

// ✅ Do this
for(let user of users) {
  console.log(user);
}
Enter fullscreen mode Exit fullscreen mode

What was it you said about easily missing the ! operator? 😁 single characters are easy to miss.

Collapse
 
melvinvmegen profile image
Melvinvmegen

Haha good catch! Failing my own rules 😕

Collapse
 
melvinvmegen profile image
Melvinvmegen • Edited

You're actually right! It's technically not an error because it works same if you do something like this :
`
test = 1;

// You can even reassign it
test = 2;

test // 2
`

But it might be var by default instead of let so either way best to specify it!

Collapse
 
merndev1101 profile image
Star

Thank you.

Collapse
 
melvinvmegen profile image
Melvinvmegen • Edited

My pleasure hope it helped!

Collapse
 
michaelcoder12 profile image
Michaelcoder12

Great post

Collapse
 
melvinvmegen profile image
Melvinvmegen

Thank you!

Collapse
 
_spurrt profile image
fuckmouth

do not use the short-if syntax, it's not considered good practice. DO use guard clauses, but do NOT use short-if syntax

Collapse
 
melvinvmegen profile image
Melvinvmegen

I like concise code but you're right it's technically not a good practice since the code block is inferred rather than explicit.

Collapse
 
masekere profile image
Gift Masekere

Using object params is really a good way of making organized and readable code, Great post

Collapse
 
melvinvmegen profile image
Melvinvmegen

Thank you! I'm glad you enjoyed it!

Collapse
 
kingkratos1827 profile image
King Kratos

In servicenow i dont think except var other var declaring can be used.

Collapse
 
kujian profile image
前端开发博客

nice advice! Can I translate it to Chinese, will keep original permalink and author. thanks!

Collapse
 
melvinvmegen profile image
Melvinvmegen

Of course you can and i'm glad you do it because i couldn't 😂

Collapse
 
michealgreat profile image
Micheal Great

Thanks...

Collapse
 
garyanu profile image
Info Comment hidden by post author - thread only accessible via permalink
gary anu

For more information you have to visit dragon city mod apk

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