How to improve the Java Script code performance
Using some below functions we can increase the JS code Performance.
a) Must use Let and Const
Rather than var developer must use the Let and Const with variables it will help you to avoid the hoisting and it also prevent the re-declaration of variable.
eg.
let a = “BlogsHub”;
let a = “Technical Blog” //Here it will give the error because a is already declare in above line its because of let
const x = {};
we can assign the value like x.type = “technical”
but we can’t re-declare like x = {}; because its already declare above
b. Must use Arrow function
Developer must use the arrow functions these are shorthand of notation of normal function and these are easy to read and write and also helpful for improve the performance of code.
For eg if you are writing ten lines code in normal function you can manage same work in two to three line using arrow function
Normal Function
let x = function(y,z){
return y * Z;
};
Arrow Function
let x = (y,z) => y*z;
c. Must use Strict Mode
JavaScript developer must use strict mode, it is a JavaScript feature to enforce strict rules for certain behaviours, which is helpful for avoid the some common mistake and make the code more secure
eg: it prevent global variable if created accidently
Syntax:
“use strict”
a = “BlogsHub” //a is not declare so it will create the error
d. Spread Function
Using the spread function we can expand the array and object in to individual element which helps to avoid the unnecessary loop and operation and increase the code performance.
eg.
let firtsemMarks = [65,70,60,80]
let secondsemMarks = [90,45,30, … firtsemMarks]
console.log(secondsemMarks)
// output [90,45,30, 65,70,60,80]
e. Promise Function
Must use promises , it is use for handle the asynchronous operations which helps to write maintainable code.
eg.
fs.promise.readFile(“filename.txt”).then(data => {
console.log(data);
}).catch(error => {
Console.log(error);
});
We can do the same things using the callback
eg.
fs.readFile(“filename.txt”, function(error,data){
if(error){
console.log(error)
}else{
Console.log(data)
});
But we should use promise rather than callback to increase the performance.
f. Use === rather ==
Always use “===” Strict equality to compare the value rather than “==”
It will help you to improve the performance.
eg.
console.log(5==”5”) //output true
console.log(5 === “5”) // output false
keep Learning 🙂