JavaScript Code Optimization Tricks and Techniques

With JavaScript Code Optimization, the code will be written as shorthand code with that we can simplify the code and write cleaner code.
Code optimization can be stated as shorthand coding which let you achieve goals with better code readability as well as code minification.

Let’s Begin With Some Most Useful JavaScript coding tricks and techniques

1. Repeat a string multiple times
//Before Code Optimization
   let str ='';
   for(i=0; i<5; i++){
    str+='Hello ';
  }
 console.log(str); //Hello Hello Hello Hello Hello

//After Code Optimization
 const str = 'Hello '.repeat(5);
2. Merging of Arrays
const arr = [50,60];

//Before Code optimization
const arr1 = arr.concat([10,20]);  //[50,60,10,20]

//After Code optimization
const arr1 = [...arr,10,20];  //[50,60,10,20]
3. Find max and min numbers in an array
const array = [10,7,20,5];

//Code Before Optimization
function max(array){
    var max= array[0];
    var min = array[0];
    for(var i=1;i<arr.length;i++){
        if(array[i]>max){
            max= array[i];
        }
        
        if(array[i]<min){
            min=array[i];
        }      
    }
    console.log("Maximum"+":"+max); //20
    console.log("Minimum"+":"+min); //5
}

//Code After Optimization
 Math.max(...array); //20
 Math.min(...array);//5

4. Exponent Power
//Longhand Code
 const power = Math.pow(4,3); //64

//Shorthand Code
const power = 4**3; //64
5. Remove duplicates from an Array
const array = [10,20,30,10,10,20,40,50];

//Code in longhand
const array = [10,20,30,10,10,20,40,50];
let uniqueArray = array.reduce(function (accumulator, currentValue) {
  if (accumulator.indexOf(currentValue) === -1) {
    accumulator.push(currentValue)
  }
  return accumulator
}, [])

console.log(uniqueArray); //[10,20,30,40,50]

//Code in shorthand
const uniqueArray =[...new Set(array)]
console.log(uniqueArray); // [10,20,30,40,50]
6. Remove falsey values from Array
const arrVal = [120, null, 0, '', undefined, false, -55, NaN, 'xyz'];

//Code in Longhand
const result = arrVal.filter(function(v){
 return v!=null && v!=undefined && v!=0 && !!v
});
console.log(result); //[ 120, -55, 'xyz' ]

//Code in Shorthand
console.log(arrVal.filter(e=>e));  //[ 120, -55, 'xyz' ]
console.log(arrVal.filter(Boolean));  //[ 120, -55, 'xyz' ]
7. Assigning Values to multiple variables
//Before Code Optimization 
let a,b,c;

a=10;
b=20;
c=30;

//After Code Optimization
let [a,b,c]=[10,20,30];
8. Swap two variables
let x ='Test';
let y = 20;

//Before Code Optimization
const temp =x;
x=y;
y=temp;

//After Code Optimization
[x,y]=[y,x];
9. Object Property Assignment

If the variable name and object key name are the same, then we can mention the variable in the object literal

const product ='computer';
const price = '50000';

//Longhand
const obj ={product:product,price:price};

//Shorthand
const obj ={product,price};
10. Multiple Condition Checking
//Unoptimized code
 if(
   value == 1 ||
   value=="one"|| 
   value==3||
   value=="test"
  ){
   //execute
  }

//Optimized code 1
if([1,'one',3,'test'].includes(value){
  //execute
});

//Optimized code 2
if ([1,'one',3,'test'].indexOf(value) >= 0) { 
   //execute
};
11. The ternary operator (If condition)
let marks = 26;

//Code before optimization
let result; 
if(marks >= 30){
 result = 'Pass'; 
}else{ 
 result = 'Fail'; 
}

//Code after optimization
let result = marks >= 30 ? 'Pass' : 'Fail'
12. Get character from string
let str = 'thecodehubs';
//Longhand 
str.charAt(2); // e

//Shorthand 
str[2]; // e
13. Flatten Nested Arrays
//Before Code Optimization
function flatten(ary) {
    var res= [];
    for(var i = 0; i < ary.length; i++) {
        if(Array.isArray(ary[i])) {
            res= res.concat(flatten(ary[i]));
        } else {
            res.push(ary[i]);
        }
    }
    return res;
}
console.log(flatten([1, [2, 3, [4, [5]], 6], 7])); //[1,2,3,4,5,6,7]

//After Code Optimization
console.log(([1, [2, 3, [4, [5]], 6], 7]).flat(Infinity)); // [1, 2, 3, 4, 5, 6, 7]


Happy Coding! 🙂

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories