FOUR SIMPLE JAVASCRIPT TRICKS THAT WILL MAKE YOUR LIFE EASY IN 2022

0
(0)

JAVASCRIPT is one of the most popular coding languages in the world. This language is a must to build the front end of any web application. Either you are using Raw  JAVASCRIPT or some other variations of it in the form of a library or a framework.

I have presented flour different tricks of JAVASCRIPT  which can reduce your coding efforts and will present you as a Pro JS Coder.

  1. USE OF TERNARY OPERATOR
// Use of Ternary operator
 
var a = 5;
var b = 6;
var c;
 
c = a>b ? a : b;
console.log("Result is: ", c);

c = a>b ? a : b;

The above line of the code is a replacing the following 6 lines f code

if( a> b) {

   c = a;

}

else {

  c = b;

}

  1. HOW TO ACCEPT INPUT IS NUMBER
// prompt-sync  ==> npm i prompt-sync
 
const prompt = require('prompt-sync')();
 
// parseInt

const num1 = 1*prompt("Enter First Number : ");
const num2 = 1*prompt("Enter Second Number : ");
const result = num1 + num2;
 
console.log("The result of addition is : ", result);

In javascript there is no strict type checking so by default it will accept character input. But we can make sure the input is number by using one of the following 

  1. parseInt()
  2. parseFloat()
  3. +
  4. ~~
  5. 1 *

And more ways 

3. SWAPPING ARRAY ELEMENTS

const arr = [4,7,9];
var temp = 0;

// using temp variable
 
[arr[0], arr[2]] = [arr[2], arr[0]];
 
console.log(arr)

           When it comes to swapping the elements we generally think of using   temp variables. But most of the time our brain can’t process it and leads to some mistakes. I have figured out a nice trick that will help you at any given point if you don’t want to use the temp variable as an option.

        3. Efficient use of FOR loops

      Rather than  using our traditional  looping 

  (let i = 0; i < arrayNum.length; i++) {
    console.log(arrayNum[i]);
  }

We can think of using some other approaches like below

Using ‘in’

for( i in arr){
  console.log(arr[i]);
}

Using ‘forEach’

arr.forEach((a)=>{
   console.log(a);
})

Hope you liked it. Please provide your valuable comments.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

Leave a Comment