JavaScript Tricks and Tips to optimize performance.
String replace
String.replace() function allows you to replace strings using String and Regex.
Basically this function replaces the string at its first occurrence. If you replace all then using replaceAll() function, use /g at the end of a Regex
Example
var string = "login login";
string.replace("in", "out"); // "logout login"
string.replace(/in/g, "out"); //"logout logout"
Using length to delete an array
Deleting n elements in an Array, use array.length.
array.length = n
Example:
var array = [1, 2, 3, 4, 5, 6];
console.log(array.length); // 6
array.length = 2;
console.log(array.length); // 2
console.log(array); // [1,2]
Merging arrays without causing server load
Merging two arrays, using Array.concat() function
var arr1 = [1, 2, 3];
var arr2 = [8, 9, 10];
console.log(arr1.concat(arr2)); // [1,2,3,8,9,10];
This function works best for small arrays.
To merge large arrays we use
Array.push.apply(arr1, arr2);
Reason is using Array.concat() function on large arrays will consume lot of memory while creating a separate new array.
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
console.log(array1.push.apply(arr1, arr2)); // [1,2,3,4,5,6];
Checking values in an Object
To check object is empty or not
Object.keys(your obj).length
0 returns if object is empty
Use switch case instead of if/else
Generally switch cases are used over if/else statements to perform almost the same tasks.
Switch statements expression to test is only evaluated once, execution time becomes less compare to if/else.
Getting the last item in the array
A smart hack is it can also accept negative values and by setting a negative number as first argument, you will get the last elements from the array.
var array = [6, 7, 8, 9, 10];
console.log(array.slice(-1)); // [10]
console.log(array.slice(-2)); // [9,10]
console.log(array.slice(-3)); // [8,9,10]