JavaScript Best Practices
Stay away from using global variables, refrain from using the new
keyword, steer clear of using ==
for comparisons, and avoid using the eval()
function.
Avoid Global Variables
Reduce the reliance on global variables.
This covers various kinds of information, items, and actions.
Other scripts can replace global variables and functions.
Utilize local variables instead and grasp the concept of closures by referring to this resource.
Always Declare Local Variables
In a function, it's important to declare all variables as local variables.
Declare local variables using the keywords var
, let
, or const
. If not declared with these keywords, local variables will turn into global variables.
Strict mode prevents using variables that haven't been declared.
Declarations on Top
Putting all declarations at the beginning of each script or function is a recommended coding practice.
This will:
- Provide cleaner code.
- Offer one location to find local variables.
- Simplify the process of avoiding unintended global variables.
- Minimize the chance of unintentional repeating 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;
The same applies to loop variables:
for (let i = 0; i < 5; i++)
{
Initialize Variables
In coding, it's smart to set values for variables right when you create them.
This will:
- Provide code that is neat and well-organized.
- Create a central location to set up variables.
- Prevent the use of 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 = {};
Setting up variables helps understand their purpose and type of data they will hold.
Declare Objects with const
Creating objects using const
ensures that their type cannot be accidentally altered.
Example
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
Declare Arrays with const
Creating arrays with the const
keyword ensures that their type cannot be accidentally altered.
Example
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()
- Replace
""
withnew String()
. - Replace
new Number()
with0
. - Replace
new Boolean()
withfalse
. - Replace
{}
withnew Object()
. - Replace
new Array()
with[]
. - Replace
new RegExp()
with/()/
. - Use
function (){}
instead of usingnew Function()
.
Beware of Automatic Type Conversions
JavaScript doesn't require strict typing.
A variable can hold different types of data.
A variable has the ability to switch its data type.
Be cautious as numbers might unintentionally turn into words or NaN
(Not a Number).
When performing math in JavaScript, numbers can be transformed into strings.
When you try to take away one string from another, it doesn't show an error. Instead, it gives you NaN
(Not a Number).
Use === Comparison
The ==
comparison operator converts values to the same type before comparing them.
The ===
operator is used to compare both the values and their types.
Use Parameter Defaults
If you forget to provide an argument when calling a function, that argument's value becomes undefined
.
Using undefined values in your code can cause it to malfunction. It's a good practice to provide default values for arguments.
ECMAScript 2015 allows default parameters in the function definition:
function (a=1, b=1) { /*function code*/ }
Learn more about function parameters and arguments by visiting the Function Parameters page.
End Your Switches with Defaults
Always include a default
at the end of your switch
statements, even if you believe it's unnecessary.
Avoid Number, String, and Boolean as Objects
Always consider numbers, strings, or booleans as basic values, not as objects.
Defining these categories as objects can reduce the speed of execution and lead to undesirable side effects.
Or, to make matters worse:
Avoid Using eval()
The eval()
function is employed to execute text as code. In most situations, there's usually no need to use it.
Due to its capability to execute any code, it poses a security concern.