Javascript is a widely-used programming language. Every web developer must get familiar with javascript to get better at web development. Moreover, Javascript provides some alternatives in every field, like React Native in app development. In a nutshell, Javascript is a great language to learn.
If you are learning Javascript or are doing it for a long time, these tricks will speed up your work. Let's have a look at them.
1. Self Calling Functions
If you want your functions to execute then and there, you can use self-calling functions.
(function(a){
console.log("It is a self calling function");
})();
2. Swapping numbers
Pretty similar to swapping numbers in python, you can swap numbers in JS as well.
var a=10;
var b= 20;
[a,b]=[b,a];
console.log(a) //20
console.log(b) //10
3. Converting String to number
To convert string to number in Javascript is a cakewalk. Add '+' in front of your string and you are done.
var a="5";
console.log(typeof(+a)) //number
4. Convert number to a string
Converting a number to a string is as easy as the above one. Have a look.
var a=5;
console.log(a+""); //"5"
5. Convert to boolean
Though there is a little need to convert to boolean in most cases, still, there is a nice way to do it in JS.
let a=0;
console.log(!!a) //false - Gives the actual Boolean value
console.log(!a) //true - Gives the complementary Boolean value.
6. Getting Random elements from the array
If you want to generate select an element randomly from an array, there is a clean way to do it in Javascript.
let teams = ['India', "Pakistan', 'Australia', 'South Africa', 'England', "West Indies', 'New Zealand']
let worldCupWinner = teams[Math.floor(Math.random()*teams.length)];
console.log("WT20 2021 winner is:", worldCupWinner); //Unfortunately not India this time
7. Generate an array of 0 to the maximum number
var arr = [] , max = 100;
for( var i=1; arr.push(i++) < max;); // numbers = [1,2,3 ... 100]
8. Getting unique values
The trick is simple, store the values of the array in Set and you are ready. If you don't know, Sets is a data structure that doesn't store duplicate values.
let arr = [1, 3, 3, 4, 5, 6, 6, 6,8, 4, 1]
let unique = [...new Set(arr)];
console.log(unique);
These were some nice tricks to work in Javascript. Comment down your suggestions.