Code should be written in such a way that everyone can understand it. In today’s time, JavaScript is a popular programming language. While writing code in JavaScript, we make some mistakes, as a result of which our code does not work properly.
So today I am going to tell you such best practices of JavaScript which are going to be very useful for you while working with JavaScript language. You can enjoy your coding journey by adopting these best practices from today itself.
1. Using var instead of let and const
Use const and let instead of var. The scope of var is global, while the scope of let and const is local. If redeclare a variable by let and const then it gives error.
//Don't use var var name = 'CodexRadar'; if(name == 'CodexRadar') { var name = 'JavaScript'; } console.log(name); //Output: JavaScript //Use const and let const name = 'CodexRadar'; if(name == 'CodexRadar') { let name = 'JavaScript'; } console.log(name); //Output: CodexRadar
2. Always Write Comments
Comments play an important role in any programming language. With the help of comments we can understand the code better. Comments should be written in short and not in paragraphs. Comments simply help us understand the code that is written.
While writing comments, we should keep the following things in mind:
- Descriptive variable/function/class names are better than descriptive comments.
- Comments should be updated according to the code over time.
- Write the comments as briefly as possible.
- Comments should always be written in simple language so that other people can understand them easily.
3. Using == instead of ===
Both operators are visually same but both are used in different way.
- Regular equality operator (==)
- Strict equality operator (===)
The Regular equality operator (==) checks only values. But the Strict equality operator (===) check values and types.
//Don't Use (==) const a = 1; const b = '1'; console.log(a==b) //Output: true //Always use (===) const a = 1; const b = '1'; console.log(a===b) //Output: false
4. Use Optional Chaining
The optional chaining operator(?) is very useful operator when we read the value of a property which is located deep in objects. This operator helps us to avoid error in our code. When we access non-existing property then we get ‘undefined‘ . Otherwise if we don’t use this operator then we get error and our code break. See below code for better understanding.
const person = { name: 'David', about: { age: 30 } } console.log(person?.about?.age) //Output: 30 console.log(person.about.education) //Output: error console.log(person?.about?.education) //Output: undefined (no error)
5. Use Magic String and Magic Number
Magic number and magic string are generally number and string which we are use directly in our code. But this is very bad practice because we don’t understand context of code. The best practice is to assign these values with const and then use it in code. This will helps us to understand the entire code with clear context.
//With Magic Number (Don't Use) validatePassword = (password) => { if(password.length > 7) console.log('Good Password') } //Without Magic Number (Always Use) const minPasswordLength = 7; validatePassword = (password) => { if(password.length > minPasswordLength) console.log('Good Password') }
6. Handling API Call Errors
Always use try/catch for handle errors with async/await. This helps us to handle errors. If we don’t use this then our code will be break and our application don’t work properly.
async function downloadImg(img = 'logo.png') { let response = await fetch(img); if(!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return await response.blob(); } //Don't use const logoImg = await downloadImg(); //Always use (Method:1) let logoImg; try { logoImg = await downloadImg(); } catch { logoImg = DEFAULT_IMG; } //Always use (Method:2) const logoImg = await downloadImg().catch(()=> DEFAULT_IMG)
7. Using multiple input parameters in objects
When declaring a function where multiple values are expected from an object. It is best to use multiple input parameters instead of single object inputs. See below code for better understanding.
//Don't use like this const getPerson = (Person)=> { console.log(`The person name is ${Person.name} and age is ${Person.age}`); } //Do this const getPerson = (name, age)=> { console.log(`The person name is ${name} and age is ${age}`); }
8. Always use abbreviations
We write a lot of code to find out if a variable is present or undefined or null, but it is not needed, instead we can write small code.
//Don't use this if(x !== "" && x !== null && x !== undefined) {...} //Do this if(!!x) {...}