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 sayfocus on having the function as small as possible. If you think itsbig find a way to break that function into smaller functions becauselarge 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 destructingconst 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 destructuringbut also assigning default values in the arguments itself whichwould help in avoiding many null and undefined exceptions andreduces developer effort to check the value whether the cost isundefined or null.Null and Type Checking: All the inputs that are entered by theuser should be validated both in front end and back end.Front end validation should be very strong and should becoded in such a way that it doesn't need any server validation.Having a strong front-end validation helps in many ways especiallySQL injection (which can affect a company with huge loss of dataand money) and also throwing an error directly in the front-endwould save us a back-end call.
For example, if a user selects a date in the front-end it should benull checked and type checked before sending it to backend.
A rule of thumb would be always "do not trust that theuser 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 underscoreeg: const DAYS_IN_WEEK = 7Saying that there are some cases where we need to usecamel case for constants likeBad 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 subjectedto 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 objectsBad 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 loggingwould be very clear as shown in the picture below.If you want to make some logs stand out/ highlight from the other logsyou can apply css to your logs like below.// Highlight logconsole.log('%c Highlight this value', 'color: green;' );Response:As a developer, performance of the application is one of the keys in making theapp successful. We can track the amount of time a function/ action took by usingconsole.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 agood idea to use.// console as a tableconsole.table([user1,user2,user3]);Response:Spread Operator: This is a new way of creating new immutable objects instead ofmutating the existing onces, react encourages us to always create immutableobjects.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 elementsinto 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 loopsGood - Using higher order functionsBad 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
Post a Comment