Before you go, check out these stories!

0
Hackernoon logo17 Interesting JavaScript Tricks by@RAHULISM

17 Interesting JavaScript Tricks

Author profile picture

@RAHULISMRahul

Front-end Web Developer and Blogger

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.

JavaScript: Tricks You Should Know

The ternary operator

Noobs:

let hungry = true;
let eat; 
if (hungry == true) {
       eat = 'yes'; 
} else {
       eat = 'no';
}

Pro:

const hungry = true;
const eat = hungry == true ? 'yes' : 'no';

Number to string / string to number

Noobs:

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

Pro:

let num = 15;
let s = num + ""; // number to string
let n = +s; // string to number

Populating an array

Noobs:

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

Pro:

let filledArray = new Array(arraysize).fill(null).mao(()=> ({'hello' : 'goodbye'}));

Dynamic properties in objects

Noobs:

let dynamic = "value"; 
let user = {
     id: 1
};
user[dynamic] = "other value";

Pro:

let dynamic = "value"; 
let user = {
    id: 1
    [dynamic] = "other value"
};
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]

Pro:

const array = [100, 23, 23, 23, 23, 67, 45]; 
const outputArray = new Set(array);
//outputArray = [100, 23, 67, 45]

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];
   }
}

Pro:

let arr = ["value1", "value2", "value3"]; 
let arrObject = {...arr}; 
Read more => Complete Guide To Fetch 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' ]

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]]

Short circuit conditionals

Noob:

if (docs) {
    goToDocs();
}

Pro:

docs && goToDocs()
Read more => "use strict" in JavaScript

Use ^ to check if numbers are not equal

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

if(a^123) // after // PRO

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 }

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

Check if value is an array

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

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]

Truthy and False values

False values => false0, 

""
(empty string)nullundefined, &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

Better way to accept arguments

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

downloadData(...); // need to remember the order

Simpler way to do:

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

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

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

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

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

⚡Thanks For Reading | Happy Coding 🍺

Previously published at https://rahulism.co/2020/11/29/_17-pro-javascript-tricks-you-didnt-know/

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.