Skip to main content

Best practices every javascript developer should be aware of

Your code is Your signature on it...

Did you face a situation where your manager suddenly comes to you and ask you to work on a business critical project with a tough deadline? Well I guess the answer is Yes for many!!! When you start looking into that project did you feel its hard to understand/ poorly documented/ not followed good practices? Well these situations happens even in big companies sometimes and there are various reasons for it mostly because of tough deadline :( Following good practices not only makes your code look readable but also makes it more secured and for sure appreciation would follow. In this blog we will share some good coding practices which when incorporated in your projects, people start appreciating you and definitely makes you more knowledgeable. When you are writing code always make sure that the other person in your project can understand everything you wrote.

Javascript Best Practices:

Writing Comments or Self Explainable code: This topic is very complicated and debatable where as some would argue that writing comments in the code makes your code more readable and easy to understand where as some would say that the code should be self explainable instead of having comments. After looking into many articles and watching many videos I found that both self explainable code and comments would help. Comments should only be used where you think that it would be difficult to make it clear.

Magic Numbers: Many novice developers often do this and I personally hate it. Whenever we know that a particular values in the code would be constant like for example number of minutes in a hour, number of days in a week and many more, for those values it is always recommended to define a constant, see example below.

Bad code:
for( let i = 0 ; i < 7 ; i++){
    // your code goes here
}
Good Code:
const DAYS_IN_WEEK = 7;
for( let i = 0 ; i < DAYS_IN_WEEK ; i++){
    // your code goes here
}

Deep Nesting & Code Repetition: It is recommended to have your code nested not more than two loops. If you are
looping more than that probably the best thing would be to check if code repetition is happening. If it does, then
extract that into a function and use it, doing this makes your code more clean.

Bad code:
myArray.forEach((arr2) => {
    arr2.forEach((arr3) => {
        arr3.forEach((data) => {
            console.log(data);
        })
    })
})
Avoid Large Functions: Someone said that any function written should 
not be more than 12 lines. Well, I don't believe in numbers I would say
 focus on having the function as small as possible. If you think its
 big find a way to break that function into smaller functions because
 large functions are difficult to keep track of and are hard to understand.
I think larger functions follows another bad practice which is code repetition.

Object Destructuring: This has become a huge topic in the recent times.  
Good thing is we don't have to create many lines of code as well as new variables to keep track of them.

Bad Code:
const getCarDetails = (car) => {
    const carName = car.name;
    const carModel = car.model;
    const carCost = car.cost;
}
Good Code:
const { name, model, cost } = car; // object destructing
const saveDetailsToDB = ({name, model, cost = 0}, save) => {
    // your code to save to db goes here
}
saveDetailsToDB(car, true);
In the above example we are not only achieving object destructuring
 but also assigning default values in the arguments itself which 
would help in avoiding many null and undefined exceptions and 
reduces developer effort to check the value whether the cost is 
undefined or null.

Null and Type Checking: All the inputs that are entered by the
user should be validated both in front end and back end.
Front end validation should be very strong and should be  
coded in such a way that it doesn't need any server validation. 
Having a strong front-end validation helps in many ways especially 
SQL injection (which can affect a company with huge loss of data
 and money) and also throwing an error directly in the front-end 
would save us a back-end call.
For example, if a user selects a date in the front-end it should be 
null checked and type checked before sending it to backend.
 A rule of thumb would be always "do not trust that the
user would enter valid data in the front end".
if(car != null) { //allow only if its not null
    
}
If you are checking any object properties always check whether the 
object is defined and then check whether the object property is defined.
Bad code:
if (car.model != null){
    // use car model value here
}
Good Code:
if(car != null && car.model != null) {
    //use car model value here
}
Variable Names: 
All variable names should follow camel case, 
eg: let userName = "pikachu@pokemon.com"
All const names should follow all caps separated by underscore 
eg: const DAYS_IN_WEEK = 7
Saying that there are some cases where we need to use 
camel case for constants like
Bad Code:
const USER = getValueFromOtherFunction();
const TODAY_DATE = new DATE();
Good Code:
const user = getValueFromOtherFunction();
const todayDate = new DATE();
The reason for that is the value on the right hand side is subjected 
to change which violates the fundamental principle of using const's.
Console Logging:
Though many take it lightly this is a huge concept and most under rated one.
When you are logging objects
Bad code:
const user1 = { name: "John", email: "john@email.com", address : "Home address" };
const user2 = { name: "Michelle", email: "michelle@email.com", address : "office address" };
const user3 = { name: "Robert", email: "robert@email.com", address : "Whatever address" };
console.log(user1);
console.log(user2);
console.log(user3);
Good code: 
console.log({user1,user2,user3});
By using the second approach we write less code and also the logging
would be very clear as shown in the picture below.

If you want to make some logs stand out/ highlight from the other logs
you can apply css to your logs like below.
// Highlight log
console.log('%c Highlight this value', 'color: green;' );
Response:

As a developer, performance of the application is one of the keys in making the 
app successful. We can track the amount of time a function/ action took by using
console.time().
let i=0;
console.time("time");
while(i<1000000){
i = i+1;
}
console.timeEnd("time");
Response:

Last but not least, if you are trying to log an array of objects this would be a
good idea to use.
// console as a table
console.table([user1,user2,user3]);
Response:
Spread Operator: This is a new way of creating new immutable objects instead of 
mutating the existing onces, react encourages us to always create immutable
objects.
Bad code:
const pikachu = {name : 'Pikachu'};
const stats = {hp : 40, attack :60, defence: 50};
const combineThem = Object.assign(pikachu,stats);
console.log(combineThem);
Good Code:
const combineThemUsingSpread = {...pikachu, ...stats};
console.log(combineThemUsingSpread);
Response (same):

Also applicable for arrays where old school method would be pushing elements 
into array and modern approach would be using a spread operator.
Bad Code:
let pokemons = ['pikachu', 'bulbasaur', 'raichu'];
pokemons.push('charmander');
pokemons.push('seedot');
console.log('%c pokemons: '+ pokemons, 'color: red');
Response:

Good Code:
pokemons = [...pokemons , 'charmander', 'seedot'];
console.log('%c pokemons: '+pokemons, 'color: green');
Response:

Loops:
Bad - Using traditional loops
Good - Using higher order functions
Bad Code :
let t=0;
for(let i=0; i< numberArray.length; i++){
t=t+numberArray[i];
}
console.log(t)


Good code: 

let total = numberArray.reduce((occ,cur) => {
return occ+cur;
})
console.log(total + ' is total');











Comments

Popular posts from this blog

Privacy Policy

**Privacy Policy for Tic Tac Toe** This privacy policy applies to the Tic Tac Toe app (hereby referred to as "Application") for mobile devices that was created by (hereby referred to as "Service Provider") as a Free service. This service is intended for use "AS IS". **Information Collection and Use** The Application collects information when you download and use it. This information may include information such as *   Your device's Internet Protocol address (e.g. IP address) *   The pages of the Application that you visit, the time and date of your visit, the time spent on those pages *   The time spent on the Application *   The operating system you use on your mobile device ...and more. The Service Provider may use the information you provided to contact you from time to time to provide you with important information, required notices and marketing promotions. For a better experience, while using the Application, the Service Provider may require...

Privacy Policy for Message Encryption

 **Privacy Policy** This privacy policy applies to the Message Encryption app (hereby referred to as "Application") for mobile devices that was created by Pushpak Kurella (hereby referred to as "Service Provider") as an Ad Supported service. This service is intended for use "AS IS". **Information Collection and Use** The Application collects information when you download and use it. This information may include information such as *   Your device's Internet Protocol address (e.g. IP address) *   The pages of the Application that you visit, the time and date of your visit, the time spent on those pages *   The time spent on the Application *   The operating system you use on your mobile device The Application does not gather precise information about the location of your mobile device. The Application collects your device's location, which helps the Service Provider determine your approximate geographical location and make use of in below ways...

Privacy Policy (message encryption pro)

 **Privacy Policy** This privacy policy applies to the Message Encryption Pro app (hereby referred to as "Application") for mobile devices that was created by Pushpak Kurella (hereby referred to as "Service Provider") as a Commercial service. This service is intended for use "AS IS". **Information Collection and Use** The Application collects information when you download and use it. This information may include information such as *   Your device's Internet Protocol address (e.g. IP address) *   The pages of the Application that you visit, the time and date of your visit, the time spent on those pages *   The time spent on the Application *   The operating system you use on your mobile device The Application does not gather precise information about the location of your mobile device. The Application collects your device's location, which helps the Service Provider determine your approximate geographical location and make use of in below way...