17 Pro JavaScript tricks you didn't know

rahxuls

Rahul

Posted on November 29, 2020

17 Pro JavaScript tricks you didn't know

There are many ways to write code but generally the first way for many people is very long and can take you some time. Here is my latest post that will increase your efficiency and productivity when coding JavaScript.


600+ Free Design resources

Image description

Resources. Freebies. Learn.
We're making things easier on Internet.

Visit - 600+ free design resources



JavaScript : Tricks You Should Know

The ternary operator

Noobs:

let hungry = true;
let eat; 
if (hungry == true) {
       eat = 'yes'; 
} else {
       eat = 'no';
}
Enter fullscreen mode Exit fullscreen mode

Pro:

let hungry = true;
let eat = hungry == true ? 'yes' : 'no';
Enter fullscreen mode Exit fullscreen mode

Number to string / string to number

Noobs:

let num = 15; 
let s = num.toString(); // number to string
let n = Number(s); // string to number
Enter fullscreen mode Exit fullscreen mode

Pro:

let num = 15;
let s = num + ""; // number to string
let n = +s; // string to number
Enter fullscreen mode Exit fullscreen mode

Populating an array

Noobs:

for(let i=0; i < arraySize; i++){
       filledArray[i] {'hello' : 'goodbye'};
}
Enter fullscreen mode Exit fullscreen mode

Pro:

let filledArray = new Array(arraysize).fill(null).map(()=> ({'hello' : 'goodbye'}));
Enter fullscreen mode Exit fullscreen mode

Dynamic properties in objects

Noobs:

let dynamic = "value"; 
let user = {
     id: 1,
};
user[dynamic] = "other value"; 
Enter fullscreen mode Exit fullscreen mode

Pro:

let dynamic = "value"; 
let user = {
    id: 1,
    [dynamic] = "other value"
};
Enter fullscreen mode Exit fullscreen mode

Read more => 3 Steps to learn a programming language

Removing duplicates

Noob:

let array = [100, 23, 23, 23, 23, 67, 45]; 
let outputArray = [];
let flag = false; 
for (j = 0; < array.length; j++) {
   for (k = 0; k < outputArray.length; k++) {
      if (array[j] == outputArray[k]) {
         flag = true;
       }
    }
    if (flag == false) {
      outputArray.push(array[j]);
     }
     flag = false;
}
//outputArray = [100, 23, 67, 45]

Enter fullscreen mode Exit fullscreen mode

Pro:

let array = [100, 23, 23, 23, 23, 67, 45]; 
let outputArray = Array.from(new Set(array)); 
//outputArray = [100, 23, 67, 45]
Enter fullscreen mode Exit fullscreen mode

Array to object

Noob:

let arr = ["value1", "value2", "value3"]; 
let arrObject = {};
for (let i = 0; i < arr.length; ++i) {
   if (arr[i] !== undefined) {
     arrObject[i] = arr[i];
   }
}
Enter fullscreen mode Exit fullscreen mode

Pro:

let arr = ["value1", "value2", "value3"]; 
let arrObject = {...arr}; 
Enter fullscreen mode Exit fullscreen mode

Read more => A guide to Geolocation API

Object to Array

Noob:

let number = {
  one: 1, 
  two: 2,
};
let keys = []; 
for (let numbers in numbers) {
  if (number.hasOwnProperty(number)) {
     keys.push(number);
    }
}
// key = [ 'one', 'two' ]
Enter fullscreen mode Exit fullscreen mode

Pro:

let number = {
  one: 1, 
  two: 2,
};
let key = Object.keys(numbers); // key = [ 'one', 'two' ]
let value = Object.values(numbers);  // value = [ 1, 2 ]
let entry = Object.entries(numbers); // entry = [['one' : 1], ['two' : 2]]
Enter fullscreen mode Exit fullscreen mode

Short circuit conditionals

Noob:

if (docs) {
    goToDocs();
}
Enter fullscreen mode Exit fullscreen mode

Pro:

docs && goToDocs()
Enter fullscreen mode Exit fullscreen mode

Read more => "use strict" in JavaScript

Use ^ to check if numbers are not equal

if(a!=123) // before // NOOBS

if(a^123) // after // PRO
Enter fullscreen mode Exit fullscreen mode

Loop over an object

const age = {
   Rahul: 20,  
   max: 16
};

// Solution 1 - Get 'keys' and loop over
const keys = Object.keys(age); 
keys.forEach(key => age[key]++);

console.log(age); // { Rahul: 21, max: 16 }

// Solution 2 - for ..in loop
for(let key in age){
   age[key]++;
}

console.log(age); // { Rahul: 22, max: 18 }
Enter fullscreen mode Exit fullscreen mode

Object keys are stored in insertion order

cosnt obj = {
  name: "Rahul", 
  age: 16, 
  address: "Earth", 
  profession: "Developer", 
}; 

console.log(Object.keys(obj)); // name, age, address, profession
Enter fullscreen mode Exit fullscreen mode

Check if value is an array

const arr = [1, 2, 3]; 
console.log(typeof arr); // object
console.log(Array.isArray(arr)); // true
Enter fullscreen mode Exit fullscreen mode

Initialize an array of size n and fill with default values

const size = 5;
const defaultValue = 0;
const arr = Array(size).fill(defaultValue);
console.log(arr); // [0, 0, 0, 0, 0]
Enter fullscreen mode Exit fullscreen mode

Truthy and False values

False values => false, 0, ""(empty string), null, undefined, &NaN.

Truthy values => "Values", "0", {}(empty object), &[](empty array)


Difference between double equal and triple equal

// Double equal - Converts both the operands to the same type and then comapares
console.log(0 == 'o'); // true

// Triple Equal - Does not convert t same type
console.log(0 === '0'); // false
Enter fullscreen mode Exit fullscreen mode

Better way to accept arguments

function downloadData(url, resourceId, searchTest, pageNo, limit) {}

downloadData(...); // need to remember the order
Enter fullscreen mode Exit fullscreen mode

Simpler way to do:

function downloadData(
{ url, resourceId, searchTest, pageNo, limit } = {}
) {}

downloadData(
  { resourceId: 2, url: "/posts", searchText: "WebDev" }
);
Enter fullscreen mode Exit fullscreen mode

null vs undefined

null => It is a value whereas undefined is not.

null is like an empty box and undefined it not box at all.

const fn = (x = 'default value') => console.log(x);

fn(undefined); // default value
fn(); // default value

fn(null); // null
Enter fullscreen mode Exit fullscreen mode

When null is passed, the default value is not taken. Whereas, when undefined or nothing is passed the default value is taken.


Need Help

Need help in raising fund to buy a Mechanical Keyboard. This pandemic has affected my family badly so can't ask my DAD for it. Please Help Me.


1.png


⚡Thanks For Reading | Happy Coding 🍺

💖 💪 🙅 🚩
rahxuls
Rahul

Posted on November 29, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

17 Pro JavaScript tricks you didn't know
javascript 17 Pro JavaScript tricks you didn't know

November 29, 2020