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:
- Variables Declarations & Initialize
- Avoid the use of a new Object()
- Use Defaults Parameter
- Common Mistakes
- Performance
- Reserved Words
- 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
-
- var firstName, lastName, fullName age;
-
-
- firstName = "John";
- lastName = "Doe";
-
- age = 19;
- 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
-
- var firstName = "",
- lastName = "",
- age = 0,
- itemPrice = 0,
- myEmployees = [],
- myEmployee = {};
Avoid to Use new Object()
We should avoid using a new object, because declaring these types as objects slows down execution speed.
- Use {} instead of new Object()
- Use "" instead of new String()
- Use 0 instead of new Number()
- Use false instead of new Boolean()
- Use [] instead of new Array()
- Use /()/ instead of new RegExp()
- Use function (){} instead of new Function()
We should use this:
- var obj1 = {};
- var strName = "";
- var myNumber = 0;
- var myBool = false;
- var myArray = [];
- var myFunction = function(){};
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:
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.
- Example:
- 0 == "";
- 1 == "1";
- 1 == true;
-
- 0 === "";
- 1 === "1";
- 1 === true;
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.
- <!DOCTYPE html>
- <html>
- <body>
- <p>Setting a default value to a function parameter.</p>
- <p id="demo"></p>
- <script>
- function myFunction(x, y) {
- if (y === undefined) {
- y = 0;
- }
- return x * y;
- }
- document.getElementById("demo").innerHTML = myFunction(4);
- </script>
- </body>
- </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:
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.
Loose Comparison
In a Loose comparison, the data type does not matter. This if statement returns true:
- <!DOCTYPE html>
- <html>
- <body>
- <p id="demo"></p>
- <script>
- var x = 10;
- var y = "10";
- document.getElementById("demo").innerHTML = Boolean(x == y);
- </script>
- </body>
- </html>
Strict comparison
In a strict comparison, data type does matter. This if statement returns false:
- <!DOCTYPE html>
- <html>
- <body>
- <p id="demo"></p>
- <script>
- var x = 10;
- var y = "10";
- document.getElementById("demo").innerHTML = Boolean(x === y);
- </script>
- </body>
- </html>
Note
Switch statements use a strict comparison:
Case-1
This case switch will display an alert:
Case-2
- <!DOCTYPE html>
- <html>
- <body>
- <p id="demo"></p>
- <script>
- var x = 10;
- switch(x) {
- case 10: alert("Hello");
- }
- </script>
- </body>
- </html>
This case switch will not display an alert:
- <!DOCTYPE html>
- <html>
- <body>
- <p id="demo"></p>
- <script>
- var x = 10;
- switch(x) {
- case "10": alert("Hello");
- }
- </script>
- </body>
- </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
- var x = 10;
- var y = 5;
- var z = x + y;
-
- var x = 10;
- var y = "5";
- var z = x + y;
Breaking a String
In JavaScript, you can break a statement into two or multiple lines:
- // Working Example :
- var x =
- "Hello World!";
But if we try to do breaking a statement in the middle of a string then it will not work:
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,
-
- var x = "Hello \
- 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:
-
- var person = [];
- person[0] = "John";
- person[1] = "Doe";
- person[2] = 46;
- var x = person.length;
- var y = person[0];
-
-
- var person = [];
- person["firstName"] = "John";
- person["lastName"] = "Doe";
- person["age"] = 46;
- var x = person.length;
- var y = person[0];
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.
-
- var i;
- for (i = 0; i < arr.length; i++) {
-
-
- var i;
- var l = arr.length;
- 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.