DEV Community

Cover image for These things you should keep in mind while writing JavaScript
Dhairya Shah
Dhairya Shah

Posted on • Originally published at codewithsnowbit.hashnode.dev

These things you should keep in mind while writing JavaScript

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
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 😊

Top comments (9)

Collapse
 
fjones profile image
FJones • Edited

I have to strongly disagree on is and has 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.

Collapse
 
thorstenhirsch profile image
Thorsten Hirsch

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 and is 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:

bool finished=false;
function hasFinished() { ... }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
fjones profile image
FJones

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).

Collapse
 
moopet profile image
Ben Sinclair

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.

Collapse
 
bytebodger profile image
Adam Nathaniel Davis • Edited

No. I'm sorry, but just... no. is and has 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 like getIsAdmin(). Given that Booleans always, by definition, only contain two possible values - true or false - it's extremely helpful to know, simply by looking at the variable name (prefaced by is or has), that the value will always hold true or false.

A function name should always start with an action verb (e.g., getUserId() or setUserId()). is and has are NOT action verbs.

Collapse
 
aneeqakhan profile image
Aneeqa Khan

Very great read!

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

I would add the glorious @JSDoc .

/** @type {boolean} */
const isAdmin = checkRole(uid);

/**
* @param {number} uid
* return {boolean}
*/
function checkRole(uid) {
  // doStuff
  return isAdmin;
}
Enter fullscreen mode Exit fullscreen mode

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 πŸ˜‚

Collapse
 
zicozydasilva profile image
Ogbu Ezekiel Ike

Cool

Collapse
 
dhairyashah profile image
Dhairya Shah

Thank You πŸ™‚

Happy Coding!