To read more articles like this, visit my blog
So you are a React developer or Node.js developer. You can write code that works. But can you write code that is visually beautiful and understandable by others?
Today we will see some rules to make your JavaScript code clean and clear.
Rule 1. Don’t Use Random Characters as Variable
Don’t use some random character to express a variable.
//BAD
const x = 4;
Name your variable properly so that it describes the value properly.
//GOOD
const numberOfChildren = 4;
Rule 2. Use camelCase Variable Name
Don’t use snake_case, PascalCase, or a variable name that starts with a verb.
// Bad: Begins with uppercase letter
var UserName = "Faisal";
-----
// Bad: Begins with verb
var getUserName = "Faisal";
-----
// Bad: Uses underscore
var user_name = "faisal";
Instead, use a camel-cased variable name that represents a noun.
// Good
const userName = "Faisal";
Rule 3. Use Good camelCase Function Name
Don’t use any noun as a function name to avoid confusion with the variable names.
// Bad: Begins with uppercase letter
function DoSomething() {
// code
}
----
// Bad: Begins with noun
function car() {
// code
}
----
// Bad: Uses underscores
function do_something() {
// code
}
Instead, start the name with a verb and use camel case.
//GOOD
function doSomething() {
// code
}
Rule 4. Use PascalCase For Constructor Function Naming
// Bad: Begins with lowercase letter
function myObject() {
// code
}
----
// Bad: Uses underscores
function My_Object() {
// code
}
----
// Bad: Begins with verb
function getMyObject() {
// code
}
Also, Constructor function names should begin with a nonverb because new is the action of creating an object instance.
// GOOD
function MyObject() {
// code
}
Rule 5. Global Constants
Global constants whose value doesn't change should not be named like normal variables.
// BAD
const numberOfChildren = 4;
// BAD
const number_of_children = 4;
They should be all upper case and separated with underscores.
// GOOD
const NUMBER_OF_CHILDREN = 4;
Rule 6. Assignment to Variable
Don’t assign a comparison value to a variable without parentheses.
// BAD
const flag = i < count;
Use parentheses around the expression:
// GOOD
const flag = (i < count);
Rule 7. Usage of Equality Operators
Don't use “==” or “!=” to compare values. Because they don't type check before comparison.
//BAD
if (a == b){
//code
}
Instead, always use “===” or “!==” to avoid type coercion errors.
//GOOD
if (a === b){
//code
}
Rule 8. Usage of the Ternary Operator
Don’t use the ternary operator as an alternative to if statement:
//BAD
condition ? doSomething() : doSomethingElse();
Only use them to assign values based on some condition:
// GOOD
const value = condition ? value1 : value2;
Rule 9. Simple Statement
Although JavaScript supports it. Don’t write multiple statements in a single line.
// BAD
a =b; count ++;
Instead, have multiple lines for multiple statements. And always use a semicolon at the end of a line.
// GOOD
a = b;
count++;
Rule 10. Use of If Statements
Don’t omit the braces from an if statement and never keep them in a single line.
// BAD: Improper spacing
if(condition){
doSomething();
}
----
// BAD: Missing braces
if (condition)
doSomething();
----
// BAD: All on one line
if (condition) { doSomething(); }
----
// BAD: All on one line without braces
if (condition) doSomething();
Always use braces and proper spacing:
// GOOD
if (condition) {
doSomething();
}
Rule 11. Usage of For Loop
Don’t declare the variable in the initialization of a for loop.
// BAD: Variables declared during initialization
for (let i=0, len=10; i < len; i++) {
// code
}
Declare them before the loop.
// GOOD
let i = 0;
for (i=0, len=10; i < len; i++) {
// code
}
Rule 12. Consistent Indentation Length
Stick to using 2 or 4 all the time.
// GOOD
if (condition) {
doSomething();
}
Rule 13. Line Length
Any line should not be more than 80 characters. If it’s more than that they should be broken up into a new line.
// BAD: Following line only indented four spaces doSomething(argument1, argument2, argument3, argument4,
argument5);
----
// BAD: Breaking before operator
doSomething(argument1, argument2, argument3, argument4
,argument5);
The second line should be indented **8 spaces **instead of 4 and shouldn't start with a separator.
// GOOD
doSomething(argument1, argument2, argument3, argument4,
argument5);
Rule 14. Primitive Literals
Strings shouldn’t use a single quote.
// BAD
const description = 'this is a description';
Instead, they should always use double-quotation
// GOOD
const description = "this is a description";
Rule 15: Use of “undefined”
Never use the special value undefined.
// BAD
if (variable === "undefined") {
// do something
}
To see if a variable has been defined, use the typeof operator
// GOOD
if (typeof variable === "undefined") {
// do something
}
So by following these rules, you can make your JavaScript projects cleaner.
These rules are taken from the book “Maintainable Javascript” written by “Nicholas C. Zakas”. So if you don’t agree with some of the points, I guess that’s fine. When it comes to styling there is no single way. But the rules here can be a good starting point for you.
That’s it for today. Happy Coding! :D
Get in touch with me via LinkedIn or my Personal Website.
Top comments (15)
Great article! From my perspective the usage of if statements on one line is very clear if the condition and the function have declarative names. I often omit the braces if I'm sure it's easy to read. :)
Nice article!
I have one more point, in my opinion, that would help to write clean code in JavaScript:
For me, this is a good helper to write clean code and visually helps to understand the code better.
What do you think?
Totally agree. Although I would go upto 3 parameters.
This rticle is well-organized and straightforward, presenting 15 distinct rules, each with its own "bad" and "good" examples.
Such a good article @mohammadfaisal thank you for sharing
Thank you!
What do you think about one-liner guards inside functions? These also stack nicely. Eg:
Very few of these rules come with any actual explanation.
Some of them do have an important purpose (consistent variable casing means a developer from any language/codebase can quickly identify classes/variables/constants, for example), but lots of these rules are purely personal preference.
I think you'd find a lot of these difficult to justify other than "that's how I do it", "it said so in a book", or "because prettier"
Maybe. But is there any universal styleguide for javascript? I guess not.
So every style guideline will ultimately fall into the "personal pereferance" bucket
There are a few "standard" rulesets for eslint, and there's prettier, but ultimately there are a lot of personal preferences - which are absolutely fine to have. However, there's a big difference between personal stylistic preferences, and practices that are intended to reduce bugs/errors.
Or in one sentence: use eslint
Eslint is a tool that helps to apply the knowledge with ease.
Eslint is not the knowledge.
sorry if this sounds offensive (I'm not trying to be) but neither is your post.
you wrote 15 rules but didn't explain why they're
good
.also, I would like to know you're reasoning regarding points 11 and 14.
I've never seen 11 in action unless you have 2 loops in a row and want to reuse variable.
regarding 14, I've seen people using both and never had any problem myself with either. and personally I prefer using single quotes because if you need to put html or json inside the string you don't need to escape it.
point 15 is just comparing apples to potatoes. it's just a mistake and no linter will help you here. so it shouldn't be in the list because you're just saying don't make this particular mistake and it has nothing to do with coding style or rules. unless you made a mistake yourself and actually meant
variable === undefined
instead in which case it warrants an explanation.I understand your point. These rules are taken from the book “Maintainable Javascript” written by “Nicholas C. Zakas”.
So obviously we will not agree on all the points. Because style is subjective.
I disagree with rules 11 and 14