Javascript hacks to show off your skills

javascript hacks to show off

According to RedMonk, JavaScript is the most popular programming language. Furthermore, SlashData estimates that around 12.4 million developers use JavaScript, which also includes CoffeeScript and Microsoft’s TypeScript.

When the language becomes this popular, people develop some hacks that help in programming and reducing the programming time. These hacks also assist you in writing cleaner code and save assets.

Let's stop wasting time in this chit-chat and jump onto the tips and tricks that can help us become better Javascript Developer.


1. Run Event Listener only Once

Yes, you heard it right, it is possible to run event listener only once without using removeEventListener.

If you want to run event listeners only once, you can use once: true as an option when adding an event listener. 

Let's check this out with help of an example.

const button = document.getElementById('button');
button.addEventListener('click' , () => {
   console.log('I will run only once');
},{once:true}) 


2. Conditional Checking in Style

Conditional checking is the most integral part of programming and is widely used.

To shorten the syntax, we can use && operator

Let's check this out with help on an example.

let condition = true;
// -- Long Way
if (condition) {
    someFunction();

}
// -- Short Way
condition && someFunction();


3.  Use 'defer' Attribute 

Defer attribute is very useful when you want to run the script when the HTML is completely loaded.

The defer attribute basically tells the browser not to wait for the script. Instead, the browser will continue to process the HTML, build DOM. The scripts load "in the background", and then run when DOM is fully built.


// -- It doesn't matter weather you place this script tag at the bottom or at the top, it will only when when the HTML is fully Loaded
<script defer src="main.js" ></script>


4.  Generate Random Number in a given range with this hack

Many times we need to generate random numbers within a given range
You can generate a random number in a given range using this hack.

function randomNumber(num1,num2) {   
    return Math.random() * (num2 - num1) + num1);
}
console.log(randomNumber(60,90)); //random number between 60 and 90 will be generated ( 60 and 90 will be inclusive )


5. Filter Duplicate values from an array

Since Sets in Javascript are a collection of unique values therefore we can use them to filter duplicate values from an array. 

let fruitArray = ["apple", "orange", "banana", "grape", "apple", "organe" ]
console.log( [...new Set(fruitArray)] );
// output -> ["apple","orange","banana","grape"]


6. Clone Object using One Line

Objects in javascript are reference types. Therefore, we can't simply use = to copy/ clone it.
So if we want to copy an object in Javascript we can use the below mentioned methods. 


const tempObj = {
  name:"tushar",
  username:"tushar98"
};
//--Using Object.assign() Method
const newObj = Object.assign({}, tempObj);
//--Using JSON
const newObj2 = JSON.parse(JSON.stringify(tempObj))
//--Using Spread Operator
const newObj3 = {...tempObj}


7. How can we check whether Object is Empty

We can use the Object.entries() method to check whether an object is empty or not

Since Object.entries() returns the array of object's enumerable properties therefore if the length of that array is 0 that means the object is empty such that the object has 0 entry.


const tempObj = {
  name:"tushar",
  username:"tushar98"
};
let emptyObj = {}
console.log(Object.entries(tempObj).length == 0) // false console.log(Object.entries(emptyObj).length == 0) // true  

8. Empty an Array in one line

In order to empty an array, we can just set its length to 0
So if next time you want to empty an array just set its length to 0 and boom the array is empty now. 

let sampleArr = ["apple", "orange", "banana", "kiwi"]
sampleArr.length = 0;
console.log(sampleArr) // output - []



Thanks for reading, please feel free to contact. 

You can check out our most active blogs as well.






Post a Comment

0 Comments