Hello Folks π
What's up friends, this is SnowBit here. I am a young passionate and self-taught frontend web developer and have an intention to become a successful developer.
Today, I am here with a few important things that you should keep in your mind while writing your JavaScript code.
Happy Reading!
Writing clean code is not a code that works, it's about readability, reused and refactored by other developers. In reality, you are not writing for yourself, you are writing for other developers who can easily read your code who can understand your code easily without any trouble editing or contributing to the project.
In this article, I will be focusing on why and how you should write clean code.
Camel Case
Camel case is the practice of writing phrases without spaces or punctuation, indicating the separation of words with a single capitalized letter, and the first word starting with either case.
Source: Wikipedia
// Don't do this β
const isadmin = true
// Do this β
const isAdmin = true
Meaningful variable names
While giving names to the variable, you should not give irrelevant or meaningless names; You should give proper names to the variable according to its job.
// Don't do this β
const foo = ["cars", "boats", "planes"]
// Do this β
const vehicles = ["cars", "boats", "planes"]
Boolean
When assigning a boolean to a variable, the name of the variable must be in interrogative tone.
The reason why you should name a boolean variable in an interrogative tone is that it is easy to find the type of the variable in little code but if you want to check the type of that variable then it becomes pretty time consuming to find that variable type and assign it a new value.
// Don't do this β
let sunday = true
// Do this β
let isSunday = true
Here, you can clearly determine the type of variable - isSunday
as you are asking Is it Sunday?
and the answer would be yes (true) or no (false) but in the case for variable sunday
you can't determine the type of that variable without viewing, here sunday
can be anything - I love sunday or I play cricket on sunday.
const isAdmin = true
const hasSubscribed = true
const hasTwitchLinked = false
Avoid extra and unnecessary context
Don't add unwanted information tot he variable name when the context is provided by the object or a class
// Don't do this β
const user = {
userName: "SnowBit",
userAge: 15,
isUserAdmin: true
}
// Do this β
const user = {
name: "SnowBit",
age: 15,
isAdmin: true
}
Avoid hardcoded values
It's better to use meaningful variables to store constant values instead of hardcoded values. It is better to keep global constants in Upper Snake Case - UPPER_SNAKE_CASE
// Don't do this β
const areaOfCircle = 3.14 * (4)^2
// Do this β
const RADIUS_OF_CIRCLE = 4
const areaOfCircle = 3.14 * (RADIUS_OF_CIRCLE)^2
So, these were some important tips that I mind sharing with you folks and I hope you enjoyed reading the article. I will be making second part of this article soon so don't forget to follow me.
Thank you for reading, have a nice day!
Your appreciation is my motivation π
- Follow me on Twitter - @codewithsnowbit
- Subscribe me on YouTube - Code With SnowBit
Top comments (9)
I have to strongly disagree on
is
andhas
prefixes for booleans. They imply a predicate, which in turn means it ought to be a function returning a boolean. The actual property itself, i.e. the variable, needn't have that. Especially with sufficient tooling that infers the type accurately.Extracting magic numbers into constants is also controversial. Comments may suffice, and the need to explain your magic 3.14 simply shouldn't exist (beyond explaining why you aren't simply using
Math.PI
). Magic numbers are an anti-pattern in the first place, but if you have them, extracting them really shouldn't help that much - since giving them a name beyond a comment doesn't solve the underlying problem either.But sometimes you just have to deal with magic numbers. Pi was a bad example since it's in the Math package, but what about "0x5F3759DF" for the fast inverse square root algorithm?
Also I think that
has
andis
do not imply a predicate. Why do you think so? I already googled, but couldn't find the answer. For me they're just prefixes that can be used for anything, so I might use them when naming (public) variables. However I would do as you suggest when writing code in a language or project which typically makes use of getter functions:Including verbs in the variable name implies an active name, i.e. a predicate.
As for magic numbers: I expect people to either know the relevant magic numbers, or to be able to infer them. Last resort being Google or comments. This, naturally, only relates to mathematical or theoretical constants. Any other magic numbers are in the definitive category of anti-patterns (see also cryptographic algorithms and the discussion surrounding e.g.
0x13579ace
or any of the constants used in SHA or MD5).Any sufficient tooling would be able to know when something's a function call or a variable. I don't think that's a useful argument, however, I think I agree with you on the booleans vs getters principle semantically.
I like to extract magic numbers and have them defined either at the top of the file, class, whatever, or to have them returned by a getter function. The former puts them all in one place and either makes it easier to refactor later.
If magic numbers are an anti-pattern, extracting pi to Math.PI is an anti-pattern, and anything that uses PI should be in a black box.
It's difficult to imagine where to draw the line.
No. I'm sorry, but just... no.
is
andhas
are very common naming conventions for Booleans - and not just in JS. If you have a function that returns whether-or-not a value is admin, it's much more conventional to name the function something likegetIsAdmin()
. Given that Booleans always, by definition, only contain two possible values -true
orfalse
- it's extremely helpful to know, simply by looking at the variable name (prefaced byis
orhas
), that the value will always holdtrue
orfalse
.A function name should always start with an action verb (e.g.,
getUserId()
orsetUserId()
).is
andhas
are NOT action verbs.Very great read!
I would add the glorious
@JSDoc
.And also agree with @fjones about verbs implying a predicate (i.e. a function returning a value).
BTW having global constants to store a dynamic value such circle radius is kinda weird, isn't it? Try to calc the area of a circle with a different radius on this implementation. I see that more like a misunderstanding about Enums (that in fact JS don't have buit in, you need TS or custom data structure to get enum-like in JS).
And finally, adding 3.14 instead using the Math API contradicts the prose around this example and will give you pretty inaccurate results, hopefully this sort of code will not be in my banking APP π
Cool
Thank You π
Happy Coding!