Thank you very much for your support on my previous blog. Here is Part 2 of "JavaScript best practices." Let's try to make clean code with these best practices:
Here is part one: click here
1:Use Template literals(``)
Template literals refer to the comma-type key that is located below Esc. This is a useful feature in Javascript.
Multi-line strings, string interpolation with embedded expressions, and tagged templates (${}) are some features of template literals.
// Error
console.log("I cannnot be written in
multiple line because I am not a template literal")
// OK
console.log(`I can be written in
multiple line because I am inside template literal`)
// Bad practice
let age = 11+1
let name= "omar"
console.log(name + " is now " + age + " years old.")
// Best practice
let name = "omar"
console.log(`${name} is now ${11 + 1} years old`)
2:Use Strong type checking(===)
There are two types of operand type checking (== & ===) in JavaScript.
The Double Equals(==) Simply compare the values of two operands. but,
The Tripple Equals(===) compares values and data types between two operands.
it is highly recommended to use strong type Tripple Equal checking(===)
// example:
4 == "4" //true
4 === "4" //false
// Bad practice
let a = "600"
if (a == 600) {
//reachable
}
// Best practice
if (a === 600) {
// not reachable
}
Note: Use == if you are aware of what you are doing.
3:Don't pollute the global prototype
If you're not familiar with prototypes in JavaScript, then you definitely should know about them.
The prototype is an object that is associated with every functions and objects by default in JavaScript.
making any changes to the prototype is called "Prototype Pollution". Avoiding making any changes to the prototype is good practice. Some developers may think that they are cool with changing the prototype but because of this, the expected behavior of javascript may get changed.
// Bad practice
String.prototype.changeString= () =>{
// implementing a random function
}
// Best practice
class changeString extends String{
newFunction(){
//implementation
}
}
let randomName = new changeString('some parameter')
4:Declare default parameter
One of the cool ES6 features is the default parameter.
If a function in JavaScript is called with missing arguments (less than declared), the missing values are set to undefined
.
Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter.
//Bad practice / Old way
function drink(beverage) {
beverage = beverage !== undefined ? beverage : "PEPSI";
return beverage
}
console.log(drink()) //PEPSI
// Best practice / ES6 way
function drink(beverage = "PEPSI") {
return beverage
}
console.log(drink()) //PEPSI
5:Use forEach instead of for loop while working with Arrays
If you are like me, then you definitely use the forEach Array method while using the DOM. We can use the for of loop to iterate over an array and run some operations in it but it is better using the forEach Array method.
// Bad practice
const myArr = [1, 2, 3, 4, 5]
for (el of myArr) {
//implementation
}
// Best practice
const myArr = [1, 2, 3, 4, 5]
function myfunction(){
//implementation
}
myArr.forEach(myfunction)
To know more about loops, check out this tweet:
6:Avoid new keyword while defining objects, strings, and Arrays
Objects, Strings, and Srrays can be defined in various ways in JavaScript. The best practice is to define by standard ways( '' for strings, {} for objects and [] for arrays).
It is not a good practice to define them with constructor functions(via the "new" keyword)
// Bad practice
const myStr = new String('I am a string')
const myObj = new Object()
myObj.name = "object name"
const myArr = new Array(1, 2, 3)
// Best practice
const myStr = "I am a string"
const myObj = {
name: "object name"
}
const myArr = [1, 2, 3]
7:Avoid using global
By default, we write code in the global scope. but suppose your code has a variable named "verify" and you have added some third-party scripts in your code. if the scripts also have a variable "verify", then your code is simply overwritten.
to avoid this problem,
give a variable a unique name
and use module pattern
// we are in the global scope
//Bad practice
function verify(){
//implementation
}
function value(){
//implementation
}
//Best practice
//module pattern
const myModule = (function () {
function verify(){
//implementation
}
function value(){
//implementation
}
reutrn{
verify,
value,
}
})();
//call them like this
myModule.verify()
myModule.value()
8: Give a Meaningful variable and function name
It is highly recommended to give a meaningful name to variables and functions. Though the names get bigger they should definitely define the purpose behind the names.
Obviously, you can give an easy name or a short name. however, as a project grows, the code gets more complex and difficult to read.
// Bad practice
const list1 = ["bread", "butter", "jam"]
const list2 = ["monkey", "lion", "cow"]
function LoginPage(){
//implement
}
//Best Practice
const shoppingList = ["bread", "butter", "jam"]
const animalList = ["monkey", "lion", "cow"]
function totalLoginAttemptsInPage(){
//implement
}
9:Use the JavaScript includes() method
Arrays and Strings both have the includes() and indexOf() methods. but if you want to be certain of any elements in a certain string or Array, use the includes() method.
It is more concise and easier to understand than Array.indexOf()
.
// normal practice
const str = "I am a string"
const arr = [1, 2, 3]
str.indexOf('s') // 7
str.indexOf('d') // -1
arr.indexOf(3) // 2
arr.indexOf(4) // -1
// Best practice
const str = "I am a string"
const arr = [1, 2, 3]
str.includes('s') // true
str.includes('d') // false
arr.includes(3) // 2
arr.includes(4) // -1
10:Strongly Avoid eval()
eval()
function gives us access to JavaScript's compiler. Basically, by supplying a string as a parameter to eval, we may execute the result of a string. Thus it gives power to the parameter and creates strong security risks.
If you're unfamiliar with it, just be aware that it is related to a security problem.
You shouldn't use it if you've already used it.
//if you run this code below in the chrome brower then the brower will refuge to deliver it. you can give it a try
eval('console.log("hi")')
Last words:
Many thanks for your encouragement on my last blog. 20 people have liked the blog. If you find this blog helpful then give it a like and comment with your important thoughts.
I try to write every Sunday. I'll be grateful if you subscribe to my newsletter.
Also, you can follow me on Twitter as am pretty much active over there and tweet daily on JavaScript and web development topics.