30 Best Practices for Clean JavaScript Code [Bonus tips at the end
<p>No waste of time. Let's go directly into it.</p>
<h1>1. Avoid Global Variables</h1>
<p><em>Bad Example</em>:</p>
<pre>
var x = 10;
function calculate() {
// Using the global variable x
return x * 2;
}j</pre>
<p><em>Good Example</em>:</p>
<pre>
function calculate(x) {
// Pass x as a parameter
return x * 2;
}
const x = 10;
const result = calculate(x);</pre>
<p>Avoid polluting the global scope with variables to prevent conflicts and improve code maintainability.</p>
<h1>2. Use Arrow Functions for Concise Code</h1>
<p><em>Bad Example</em>:</p>
<pre>
function double(arr) {
return arr.map(function (item) {
return item * 2;
});
}</pre>
<p><em>Good Example</em>:</p>
<pre>
const double = (arr) => arr.map((item) => item * 2);</pre>
<p>Arrow functions provide a concise and more readable way to define small functions.</p>
<h1>3. Error Handling with Try-Catch Blocks</h1>
<p><em>Bad Example</em>:</p>
<pre>
function divide(a, b) {
if (b === 0) {
return "Division by zero error!";
}
return a / b;
}</pre>
<p><em>Good Example</em>:</p>
<pre>
function divide(a, b) {
try {
if (b === 0) {
throw new Error("Division by zero error!");
}
return a / b;
} catch (error) {
console.error(error.message);
}
}</pre>
<p>Use try-catch blocks to handle errors gracefully and provide meaningful error messages.</p>
<p><a href="https://nikitrauniyar.medium.com/30-best-practices-for-clean-javascript-code-bonus-tips-at-the-end-d83755d7cc4f">Read More</a></p>