In this guide, we'll explore best practices for writing efficient and clean JavaScript code. These practices emphasize avoiding global variables, proper variable declaration, type handling, avoiding the eval()
function, and more.
1. Minimize Global Variables
Global variables should be avoided to prevent unintended modifications and conflicts. Utilize local variables and closures to encapsulate your code.
2. Always Declare Local Variables
Declare variables using var
, let
, or const
within their appropriate scopes to avoid unexpected global declarations.
let firstName = "";
let lastName = "";
const price = 0;
const discount = 0;
let fullPrice = 0;
const myArray = [];
const myObject = {};
Note:- Strict mode does not allow undeclared variables.
3. Declarations at the Top
Place all variable declarations at the beginning of your script or function. This will:
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;
This also goes for loop variables:
for (let i = 0; i < 5; i++) {
4. Initializing Variables
Always initialize variables during declaration to provide clarity and avoid undefined values. This will:
Give cleaner code
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 = {};
Note:- Initializing variables provides an idea of the intended use (and intended data type).
5. Declare Objects and Arrays with const
Use const
to declare objects and arrays to prevent accidental changes in 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
6. Avoid Unnecessary use of 'new'
Avoid using new
for primitive types. Instead, use literals for better performance.
Use "" instead of new String()
Use 0 instead of the 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
7. Be Cautious of Type Conversions
JavaScript is loosely typed, so be aware of automatic type conversions to prevent unexpected behavior.
A variable can change its data type:
let x = "Hello"; // typeof x is a string
x = 5; // changes typeof x to a number
Beware that numbers can accidentally be converted to strings or NaN (Not a Number).
When doing mathematical operations, JavaScript can convert numbers to strings:
let x = 5 + 7; // x.valueOf() is 12, typeof x is a number
let x = 5 + "7"; // x.valueOf() is 57, typeof x is a string
let x = "5" + 7; // x.valueOf() is 57, typeof x is a string
let x = 5 - 7; // x.valueOf() is -2, typeof x is a number
let x = 5 - "7"; // x.valueOf() is -2, typeof x is a number
let x = "5" - 7; // x.valueOf() is -2, typeof x is a number
let x = 5 - "x"; // x.valueOf() is NaN, typeof x is a number
Subtracting a string from a string does not generate an error but returns NaN (Not a Number):
"Hello" - "Dolly" // returns NaN
8. Use Strict Equality Comparison (===)
The == comparison operator always converts (to matching types) before comparison.
The === operator forces a comparison of values and types:
0 == ""; // true
1 == "1"; // true
1 == true; // true
0 === ""; // false
1 === "1"; // false
1 === true; // false
9. Handle Function Parameters Gracefully
Assign default values to function parameters to handle missing arguments effectively.
function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
}
ECMAScript 2015 allows default parameters in the function definition:
function (a=1, b=1) { /*function code*/ }
Read more about function parameters and arguments at Function Parameters
10.End Your Switches with Defaults
Always end your switch statements with a default. Even if you think there is no need for it.
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
default:
day = "Unknown";
}
11.Avoid Number, String, and Boolean as Objects
Always treat numbers, strings, or booleans as primitive values. Not as objects.
Declaring these types as objects slows down execution speed, and produces nasty side effects:
let x = "John";
let y = new String("John");
(x === y) // is false because x is a string and y is an object.
Or even worse:
let x = new String("John");
let y = new String("John");
(x == y) // is false because you cannot compare objects.
12. 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.
By following these best practices, you can write more efficient, maintainable, and secure JavaScript code. Happy coding!