5 Simple and powerful JavaScript hacks

  • 1. Null Filtering

Some time we got some payload of array from external sources and we need to filter out the null values from array to process further. Below is very simple and power full trick to perform this task.

var datas = ["hi","hello",null,"you",null,"me"]
datas= datas.filter(function(n) {
 return n
 });
//Output will be
Output: ["hi","hello","you","me]
  • 2. Replace with Regex

By default replace method replace the first occurrence of the match, but if we need to replace all the occurrence of the match then we can take help of regex, they are very powerful. You can learn test and debug the regex at this site https://regexr.com/.

var sampleString = "login logout signin signout"; 
console.log(sampleString.replace("in", "out")); 
// output: "logout logout signin signout" 
console.log(sampleString.replace(/in/g, "out")); 
// output: "logout logout signout signout"
  • 3. ~~ for float to integer conversion

We often use standard math function to convert float to integer like math.floormath.ceil and math.round for eliminating decimals. There is very less used and very optimized operator is available to this purpose “~~” to eliminate decimals for a value.

var number=math.random;
~~ (number/2)
in place of
math.round(number/2);
  • 4. Trimming and clearing array using length property

Array length property can be used to trim the array to specific length or even to clear the array.

var dArray = [1, 2, 3, 4, 5, 6,8]; 
console.log(dArray .length); 
// output: 7 
//To trim the array to three element 
dArray.length = 3; 
console.log(dArray.length); 
// output 3 
console.log(dArray); 
// output [1,2,3]

//To clear the array

dArray.length = 0;
console.log(dArray.length); 
// output 0 
console.log(dArray); 
// output []
  • 5 Fetching Items from Array from the end (last, last n)
var array = [1, 2, 3, 4, 5, 6, 8]; 
console.log(array.slice(-1)); // [8] 
console.log(array.slice(-2)); // [6,8] 
console.log(array.slice(-3)); // [5,6,8]

Bonus (Default value if variable undefined)

var obj={};
//operation where obj is being populated
......
var j = obj.k || "default";
console.log(j);
//if k has value then  output: value
//else output: default 

Thanks for reading, hope you enjoyed the article.

you're currently offline