Loading Please Wait...

Logo Lynxsia IT Solutions

JavaScript Best Practice

JS Best Practice

This tutorials guide you to write better code.

Avoid Global Variables

Minimize the use of global variables.

This includes all data types, objects, and functions.

Global variables and functions can be overwritten by other scripts.

Use local variables instead, and learn how to use closures.

Always Declare Local Variables

All variables used in a function should be declared as local variables.

Local variables must be declared with the var, the let, or the const keyword, otherwise they will become global variables.

Global variables and functions can be overwritten by other scripts.

Use local variables instead, and learn how to use closures.

Declarations on Top

It is a good coding practice to put all declarations at the top of each script or function. This also goes for loop variables.

  • Give cleaner code
  • Provide a single place to look for local variables
  • Make it easier to avoid unwanted (implied) global variables
  • Reduce the possibility of unwanted re-declarations
					 
        
          // Declare at the beginning
          let firstName, lastName, price, discount, fullPrice;

          // Use later
          firstName = "John";
          lastName = "Doe";

          price = 19.90;
          discount = 0.10;

          fullPrice = price - discount;

          for (let i = 0; i < 5; i++) {}
        
      
Initialize Variables

It is a good coding practice to initialize variables when you declare them. Initializing variables provides an idea of the intended use (and intended data type).

  • Give cleaner code
  • Provide a single place to look for local variables
  • Provide a single place to initialize variables
  • Avoid undefined values
					 
        
          // Declare and initiate at the beginning
          let firstName = "";
          let lastName = "";
          let price = 0;
          let discount = 0;
          let fullPrice = 0,
          const myArray = [];
          const myObject = {};
        
      
Declare Arrays or Objects with const

Declaring arrays or objects with const will prevent any accidental change of type

					 
        
          let car = {type:"Fiat", model:"500", color:"white"};
          car = "Fiat";      // Changes object to string

          const car = {type:"Fiat", model:"500", color:"white"};
          car = "Fiat";      // Not possible

          let cars = ["Saab", "Volvo", "BMW"];
          cars = 3;    // Changes array to number

          const cars = ["Saab", "Volvo", "BMW"];
          cars = 3;    // Not possible
        
      
Don't Use new Object()

It is a good coding practice to initialize variables when you declare them. Initializing variables provides an idea of the intended use (and intended data type).

  • Use "" instead of new String()
  • Use 0 instead of new Number()
  • Use false instead of new Boolean()
  • Use {} instead of new Object()
  • Use [] instead of new Array()
  • Use /()/ instead of new RegExp()
  • Use function (){} instead of new Function()
					 
        
          let x1 = "";             // new primitive string
          let x2 = 0;              // new primitive number
          let x3 = false;          // new primitive boolean
          const x4 = {};           // new object
          const x5 = [];           // new array object
          const x6 = /()/;         // new regexp object
          const x7 = function(){}; // new function object
        
      
Beware of Automatic Type Conversions

JavaScript is loosely typed.

A variable can contain all data types.

A variable can change its data type.

					 
        
          let x = "Hello"; // typeof x is a string
          x = 5;           // changes typeof x to a number
        
      
Use === Comparison

The == comparison operator always converts (to matching types) before comparison.

The === operator forces comparison of values and type.

					 
        
          0 == "";    // true
          1 == "1";   // true
          1 == true;  // true

          0 === "";   // false
          1 === "1";  // false
          1 === true; // false
        
      
Use Defaults Parameter

If a function is called with a missing argument, the value of the missing argument is set to undefined.

Undefined values can break your code. It is a good habit to assign default values to arguments.

					 
        
          function myFunction(x, y) {
            if (y === undefined) {
              y = 0;
            }
          }

          function (a=1, b=1) { /*function code*/ }
        
      
Avoid Using eval()

The eval() function is used to run text as code. In almost all cases, it should not be necessary to use it.

Because it allows arbitrary code to be run, it also represents a security problem.

How you feel about this blog:

Share this blog on:

Report Us

If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com

Contact Us
Ads
Logo
Lynxsia IT Solutions

We are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..

Kotwali Road, Chhiptehri, Banda, 210001, UP, India

Copyright © 2022, Lynxsia IT Solutions, All rights reserved