JavaScript Best Practices

Introduction 

 
Dear reader, as we know, coding with best practices is an art of interest. Before we start to write our code, we should learn about good code examples. In this article, I will try to cover the best practices.
 
So let's cover the following:
  1. Variables Declarations & Initialize
  2. Avoid the use of a new Object()
  3. Use Defaults Parameter
  4. Common Mistakes
  5. Performance
  6. Reserved Words
  7. Summary

Variables Declarations & Initialize

 
For any data setting or getting, we need to use variables.
 
We have 2 types of variables,
  • Local Variable: variables that we declare inside function is called local variable
  • Global Variable: variables that we declare outside function is called global variable
Note
  • With any function, local variables must be declared with the [var] keyword or the [le]t keyword, otherwise, it will become global variables. So the good practices is to declare any variables on top, because of that when you declare on top you will get couple of advantage, 
  • Cleaner code
  • Provides a single place to look for local variables
  • Makes it easier to avoid unwanted (implied) global variables
  • Reduces the possibility of unwanted re-declarations
Example
  1. // Declare at the beginning  
  2. var firstName, lastName, fullName age;  
  3.   
  4. // Use later  
  5. firstName = "John";  
  6. lastName = "Doe";  
  7.   
  8. age = 19;  
  9. fullName = firstName + lastName;  
Initialize Variables
 
It is a good coding practice to initialize the variable at the time of declarations. This way we can avoid undefined values.
 
Example
  1. // Declare and initiate at the beginning  
  2. var firstName = "",  
  3. lastName = "",  
  4. age = 0,  
  5. itemPrice = 0,  
  6. myEmployees = [],  
  7. myEmployee = {};  

Avoid to Use new Object()

 
We should avoid using a new object, because declaring these types as objects slows down execution speed.
  1. Use {} instead of new Object()  
  2. Use "" instead of new String()  
  3. Use 0 instead of new Number()  
  4. Use false instead of new Boolean()  
  5. Use [] instead of new Array()  
  6. Use /()/ instead of new RegExp()  
  7. Use function (){} instead of new Function()  
We should use this:
  1. var obj1 = {}; // new object  
  2. var strName = ""// new primitive string  
  3. var myNumber = 0; // new primitive number  
  4. var myBool = false// new primitive boolean  
  5. var myArray = []; // new array object  
  6. var myFunction = function(){}; // new function object  
Automatic Type Conversions
 
As we know, scripting type is declared as dynamic, for example, we use var a="N1"; so it will be string type and if we use var a1 =1, so it will be number type. But do you know when we declare the following:
  1. var a ="N1"// typeof a is a string  
  2. a =5; // changes typeof a to a number  
Here you can see that without any type casting variable, a becomes number type. Use the === Comparison.
 
Many times we need to compare 2 value, so == and === is the option to do that. So the good practice we should use that ===, because the === comparison operator always converts (to matching types) before comparison. === operator forces comparison of values and type.
  1. Example:  
  2. 0 == ""// true  
  3. 1 == "1"// true  
  4. 1 == true// true  
  5.   
  6. 0 === ""// false  
  7. 1 === "1"// false  
  8. 1 === true// false  

Use Defaults Parameter

 
As we know, any function can be with or without a parameter, in the case of a parameterized function, we should use that default parameter. Otherwise, a function is called with a missing argument, and the value of the missing argument is set as undefined.
 
Undefined values can break your code. It is a good habit to assign default values to arguments.
  1. <!DOCTYPE html>    
  2. <html>    
  3. <body>    
  4. <p>Setting a default value to a function parameter.</p>    
  5. <p id="demo"></p>    
  6.    <script>    
  7.       function myFunction(x, y) {    
  8.          if (y === undefined) {    
  9.          y = 0;    
  10.          }    
  11.          return x * y;    
  12.       }    
  13.    document.getElementById("demo").innerHTML = myFunction(4);    
  14. </script>    
  15. </body>    
  16. </html>    
In this function, we use 2 parameters. However, at the time of calling, I use only 1 parameter. In this case, the parameter y will be undefined. It's better to use a default parameter like with this function:
  1. function (x=1, y=1)  
  2. {  
  3.    /*function code*/  
  4. }  
Common Mistakes
 
Here is an assignment Operator mistake. Suppose that we are going to compare the value but my mistake we can use = while we should use == otherwise we will get an unexpected result.
  1. // Bad  
  2. if (x = 10)  
  3.   
  4. // Good  
  5. if (x == 10)  
Loose Comparison
 
In a Loose comparison, the data type does not matter. This if statement returns true:
  1. <!DOCTYPE html>    
  2. <html>    
  3. <body>    
  4. <p id="demo"></p>    
  5.    <script>    
  6.       var x = 10;    
  7.       var y = "10";    
  8.       document.getElementById("demo").innerHTML = Boolean(x == y);    
  9.    </script>    
  10. </body>    
  11. </html>    
Strict comparison
 
In a strict comparison, data type does matter. This if statement returns false:
  1. <!DOCTYPE html>    
  2. <html>    
  3. <body>    
  4. <p id="demo"></p>    
  5.    <script>    
  6.       var x = 10;    
  7.       var y = "10";    
  8.       document.getElementById("demo").innerHTML = Boolean(x === y);    
  9.    </script>    
  10. </body>    
  11. </html>    
Note
Switch statements use a strict comparison:
 
Case-1
 
This case switch will display an alert:
 
Case-2
  1. <!DOCTYPE html>    
  2. <html>    
  3. <body>    
  4. <p id="demo"></p>    
  5.    <script>    
  6.       var x = 10;    
  7.       switch(x) {    
  8.       case 10: alert("Hello");    
  9.       }    
  10.    </script>    
  11. </body>    
  12. </html>    
This case switch will not display an alert:
  1. <!DOCTYPE html>    
  2. <html>    
  3. <body>    
  4. <p id="demo"></p>    
  5.    <script>    
  6.       var x = 10;    
  7.       switch(x) {    
  8.       case "10": alert("Hello");    
  9.    }    
  10. </script>    
  11. </body>    
  12. </html>     
Confusing Addition & Concatenation
 
When we do both integer then Addition is about adding numbers. when we do 1 integer and other string then Concatenation is about adding strings. Here In JavaScript both operations use the same + operator.
 
Example
  1. var x = 10;  
  2. var y = 5;  
  3. var z = x + y; // the result in z is 15  
  4.   
  5. var x = 10;  
  6. var y = "5";  
  7. var z = x + y; // the result in z is "105"  
Breaking a String
 
In JavaScript, you can break a statement into two or multiple lines:
  1. // Working Example :  
  2. var x =  
  3. "Hello World!";  
But if we try to do breaking a statement in the middle of a string then it will not work:
  1. // Not Working Example:  
  2. var x = "Hello  
  3. World!";  
so for that we want to do like that , then we need to use backslash" if we really want to break a statement in a string,
  1. // Working Example:  
  2. var x = "Hello \  
  3. World!";  
Accessing Arrays with Named Indexes
 
As we know that many programming languages are supporting arrays called with named indexes. But in JavaScript does not support arrays with named indexes.
 
Here in JavaScript array called only my numberIndexed:
  1. // Number Index Example:  
  2. var person = [];  
  3. person[0] = "John";  
  4. person[1] = "Doe";  
  5. person[2] = 46;  
  6. var x = person.length; // person.length will return 3  
  7. var y = person[0]; // person[0] will return "John"  
  8.   
  9. // Named Example  
  10. var person = [];  
  11. person["firstName"] = "John";  
  12. person["lastName"] = "Doe";  
  13. person["age"] = 46;  
  14. var x = person.length; // person.length will return 0  
  15. var y = person[0]; // person[0] will return undefined  

Performance

 
As we know that we can meet to write the code for business requirement. However, perfomance is a key part of any software application. We should use a better coding practice to avoid issues with slowness.
 
It's good to reduce activity in loops. As we know, loops are often used in programming.
  1. // Bad:  
  2. var i;  
  3. for (i = 0; i < arr.length; i++) {  
  4.   
  5. // Good:  
  6. var i;  
  7. var l = arr.length;  
  8. for (i = 0; i < l; i++) {  
Here, bad code accesses the length property of an array each time the loop is iterated.
 

Reserved Words

 
In any application, we can't use reserved keywords. It's the same in Javascript, you cannot use these reserved words.
 
 

Summary

Our practices are now completed. So dear reader, always use this. Congratulations on following the steps and reaching out here. I hope you liked this tutorial and please share it with others.
 
Thanks for taking your valuable time to read the full article.