Digital Transformation in HealthCare Solution

Tech Talk

JavaScript Tips, Tricks and Best Practices

17 MAY 2021

Hello Developers! In this tech article I will cover JavaScript Trips, Tricks and Best Practices. In daily coding many times we wrote a long lines of code, read this article I am going to cover best javascript practices, tips & tricks to reduce lines of code and minimize your works using JavaScript in-built functions. I will cover array of JavaScript function along with example right away, So Let's Start!

Key Points -

  • Replace All
  • Group By Array Of Objects
  • Next - next()
  • Map - map()
  • Cast Values in array using - map()
  • Filter - filter()
  • Find Index - findIndex()
  • Best Practice - Avoid If/Else | Switch
  • Destructuring Assignment - Smart Tips!
  • Numeric Separators
  • Get Unique Elements || Remove Duplicate Objects From Array -
  • Promise Any
  • Logical Assignment Operators
  • Get The Last Item From Array
  • Get Function Arguments using arguments
  • Sort Array

1. Replace All - replaceAll(arg1, arg2)

replaceAll('arg1', 'arg2') - Easily replace all the characters that you specify in a string without using a regex. It takes two arguments, arg1 - the character you want to replace and arg2 - the character you want to replace it by.


const string = "Javascript is the best web scripting language. Javascript can be used for both front end and backend";
console.log(string.replace("Javascript", "Typescript"));

// output: Typescript is the best web scripting language. Typescript can be used for both front end and backend

let myStr = ‘Prograssing’;
console.log(myStr.replaceAll(“s”, “m”)); //output: Programming

2. Group By Array Of Objects - reduce()

Very Important Tricks - Many times we need to group result from array, Let's check how reduce() help us to achieve, over here I have sent two arguments: arg1 - arrCity (array), arg2 - region (key-name - on which you want to apply group)


var arrCity = [
  {'region': 'Europe', 'name': 'Paris'},
  {'region': 'Europe', 'name': 'Amsterdam'},
  {'region': 'Europe', 'name': 'Vienna'},
  {'region': 'UnitedStates', 'name': 'New York'},
  {'region': 'UnitedStates', 'name': 'San Francisco'},
  {'region': 'Europe', 'name': 'Barcelona'},
 ]
 
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
  (rv[x[key]] = rv[x[key]] || []).push(x);
  return rv;
  }, {});
};

var resultByRegion = groupBy(arrCity, 'region'); // pass array & key-name

console.log(resultByRegion);
//output: 
{
  Europe: [
    {name: "Paris", region: "Europe"}, 
    {name: "Amsterdam",region: "Europe"}, 
    {name: "Vienna",region: "Europe"}, 
    {name: "Barcelona",region: "Europe"}
  ],
  UnitedStates: [
    {name: "New York",region: "UnitedStates"}, 
    {name: "San Francisco",region: "UnitedStates"}
  ]
}

3. Next - next()

Many times we are required to take a unique number for our business logic and we try random functions but it might chance it will repeat the same number again. Try next() will give you a unique number every time.


function* getUniqueID() {
  var uniqueNumber = 0;
  while (true) {
    yield uniqueNumber++;
  }
}

const uniqueID = getUniqueID();

console.log(uniqueID.next().value); // output: 0
console.log(uniqueID.next().value); // output: 1
console.log(uniqueID.next().value); // output: 2

4. Map - map()

Map is widely used by developers in daily coding, Map offers various use cases depending upon your custom requirement. Let's check in code,


var arrCity = [
  {
  'id': 1,
  'name': 'London',
  'region': 'UK',
  },
  {
  'id': 2,
  'name': 'Paris',
  'region': 'Europe',
  },
  {
  'id': 3,
  'name': 'New York',
  'region': 'United State',
  },
 ]
 
 const arrCityName = arrCity.map(city => city.name);
 console.log(arrCityName); // output: ['London', 'Paris', 'New York']

Many times we required to add new key-pari within existing array, Let's do that,


// Let's use arrCity over here,

arrCity.map(city => city.cityWithName = city.name + ' - ' + city.region);
console.log(arrCity); 

// output: 
[{
  cityWithName: "London - UK", // new key-pair 
  id: 1,
  name: "London",
  region: "UK"
}, {
  cityWithName: "Paris - Europe", // new key-pair 
  id: 2,
  name: "Paris",
  region: "Europe"
}, {
  cityWithName: "New York - United State", // new key-pair 
  id: 3,
  name: "New York",
  region: "United State"
}]

Let's use another approach and add new key-pair value,


// We will use same array - arrCity over here,

const newArrCity = arrCity.map((city) => ({
  ...city,
  newCity: true,
}));
console.log(newArrCity); 

// output: 
[{
  id: 1,
  name: "London",
  newCity: true, // new key-pair 
  region: "UK"
}, {
  id: 2,
  name: "Paris",
  newCity: true, // new key-pair 
  region: "Europe"
}, {
  id: 3,
  name: "New York",
  newCity: true, // new key-pair 
  region: "United State"
}]

5. Cast Values in array using - map()

Awesome tricks - harness the power of map function you will convert an array of strings into an array of numbers.


const arrStringValues = ['1', '2', '3', '4.567', '-89.95', [1.2345]];
const arrNumbers = arrStringValues.map(Number);

console.log(arrNumbers); // output: [1, 2, 3, 4.567, -89.95, 1.2345]

6. Filter - filter()

Consider you have an array and you want to take only relevant data, use filter() and apply your criteria it will return you filter result.


var arrCity = [
  {'region': 'Europe', 'name': 'Paris'},
  {'region': 'Europe', 'name': 'Amsterdam'},
  {'region': 'Europe', 'name': 'Vienna'},
  {'region': 'UnitedStates', 'name': 'New York'},
  {'region': 'UnitedStates', 'name': 'San Francisco'},
  {'region': 'Europe', 'name': 'Barcelona'},
 ]
 
const arrEuropeCity = arrCity.filter(city => city.region === 'Europe')

console.log(arrEuropeCity); 

output:
[
  {name: "Paris", region: "Europe"}, 
  {name: "Amsterdam", region: "Europe"}, 
  {name: "Vienna", region: "Europe"},
  {name: "Barcelona", region: "Europe"}
]

7. Find Index - findIndex()

Very useful on daily coding - It's simple trick to find index of object from array


const arrCity = [
  {'id':'1', 'name':'London'},
  {'id':'2', 'name':'Paris'},
  {'id':'3', 'name':'New York'}
];

const index = arrCity.findIndex(city => city.name === 'Paris');
console.log(index); // output: 1

8. Best Practice - Avoid If/Else | Switch

Many times we write conditional code, either we use if/else Or switch, I would suggest best code practice here and use smart trick, Let's check how it is going with If/Else,


function getCityInformation(city) {
  if (city.toLowerCase() === "london") {
    return "Welcome to London!";
  } else if (rhyme.toLowerCase() === "paris") {
    return "Welcome to Paris!";
  } else if (rhyme.toLowerCase() === "amsterdam") {
    return "Welcome to Amsterdam!";
  }

  return "We're Sorry, No City Found!";
}
const londonCityInfo = getCityInformation('London');

console.log(londonCityInfo); // output: Welcome to London!

Let's avoid If/Else OR Switch and use our TRICK here,


function getCityInformation(city) {
  const cityInfo = {
    "london": "Welcome to London!",
    "paris": "Welcome to Paris!",
    "amsterdam": "Welcome to Amsterdam!",
  };
  
  return cityInfo[city.toLowerCase()] ?? "We're Sorry, No City Found!";
}
const pariseCityInfo = getCityInformation('Paris');

console.log(pariseCityInfo); // output: Welcome to Paris!

9. Destructuring Assignment - Smart Tips!

All you know about props extractor very well, its bit similar kind of syntax where you can give ALIAS_NAME which you extract from object which return you the smart result, Let's Check,


const region = {
  "id": 1,
  "name": "Europe",
  "city": ['Paris', 'Vienna', 'Amsterdam'],
};

const {id, name} = region;
const {0: paris, 2: amsterdam} = region.city;

console.log(id); // 1
console.log(name); // Europe
console.log(paris); // Paris
console.log(amsterdam); // Amsterdam

10. Numeric Separators

Numeric separators are one of the useful features that have been introduced in ES2021. This makes it easier to read large numbers in JavaScript by providing separation between digits using underscores _.


let myNumber = 3_000_000;
console.log(myNumber); //output: 3000000

let num = 0.000_0003;
console.log(num); //output: 3e-7

11. Get Unique Elements || Remove Duplicate Objects From Array

What do you do to get unique elements from an array, manual iterate and check if an element exists or not? Let's try Set function to get unique results -


const arrIndex = [1,2,3,4,5,3,7,9,1,6,8,0];
const arrCity = ['Paris', 'London', 'New York', 'Paris' , 'Chicago'];

const uniqueIndex = [...new Set(arrIndex)];
const uniqueCity = [...new Set(arrCity)];

console.log(uniqueIndex); // output: [1, 2, 3, 4, 5, 7, 9, 6, 8, 0]
console.log(uniqueCity); // output: ["Paris", "London", "New York", "Chicago"]

12. Promise Any

Promise.any() takes an array of promises as an argument. If all the promises are resolved, then only it will return a result. It will wait until all promises complete their tasks, no matter whether it's resolve, reject.


 const promise1 = new Promise((resolve, reject) => {
  resolve(‘promise1 was resolved.’);
 });
 const promise2 = new Promise((resolve, reject) => {
  resolve(‘promise2 was resolved.’);
 });
 const promise3 = new Promise((resolve, reject) => {
  resolve(‘promise3 was resolved.’);
 });
 let result = Promise.any([promise1, promise2, promise3]);
 console.log(result); //output: promise1 was resolved. promise2 was resolved. promise3 was resolved.

13. Logical Assignment Operators

ES2021 come out with three useful logical assignment operators: &&= , ||= , and ??= .

The logical assignment operator &&= is used between two values. If the first value is truthy, the second value will be assigned to it.


let firstNumber = 5;
let secondNumber = 20;
firstNumber &&= secondNumber; //output: 20
console.log(firstNumber); //output: 20
//Here is an equivalent to it:
if(firstNumber){
  firstNumber = secondNumber;
}

The logical assignment operator ||= is also used between two values. If the first value is not truthy(falsy), the second value will be assigned to it.


let firstNumber = null;
let secondNumber = 10;
firstNumber ||= secondNumber; //output: 10
console.log(firstNumber); //output: 10
//Here is an equivalent to it:
if(!firstNumber){
 firstNumber = secondNumber;
}

The logical assignment operator ??= checks if the first value is null or undefined. If it is, the second value is assigned to it.


//when first value is null or undefined
let firstNumber = null;
let secondNumber = 10;
firstNumber ??= secondNumber; //output: 10
console.log(firstNumber); //output: 10
//when first value is truthy
firstNumber = 9;
firstNumber ??= secondNumber; //output: 9
console.log(firstNumber); //output: 9
//Here is an equivalent to it:
if(firstNumber == null || firstNumber == undefined){
 firstNumber = secondNumber;
}

14. Get The Last Item From Array

Using slice() function by passing negative index, it will take value from end of array,


let array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log(array.slice(-1)); // output [9]
console.log(array.slice(-2)); // output: [8, 9]
console.log(array.slice(-3)); // output: [7, 8, 9]

console.log(array.slice(1)); // output [2, 3, 4, 5, 6, 7, 8, 9]
console.log(array.slice(2)); // output: [3, 4, 5, 6, 7, 8, 9]
console.log(array.slice(3)); // output: [4, 5, 6, 7, 8, 9]

15. Get Function Arguments using arguments

No more need of giving function argument name in function, using javascript arguments you can receive function arguments.


function sumOfValues(){

  let sum = 0;

  console.log(arguments[0]); // output: 1
  console.log(arguments[1]); // output: 2
  console.log(arguments[2]); // output: 3
  
  for(index in arguments) {
    sum += arguments[index]
  }
	
  return sum;
}

const sum = sumOfValues(1,2,3,4,5);
console.log(sum); // output: 15

16. Sort Array

Sort Array Of Objects


const array = [
  { "name": "student1", "marks": 72},
  { "name":"student2","marks": 95},
  { "name": "student3", "marks": 89},
]
  
const acendingResult = array.sort(function (a, b) {
  return a.marks - b.marks;
});
console.log(acendingResult);
// output
[
  { marks: 72,  name: "student1"}, 
  { marks: 89,  name: "student3"}, 
  { marks: 95,  name: "student2"}
]
  
const decendingResult = array.sort(function (a, b) {
  return b.marks - a.marks;
});
console.log(decendingResult);
// output
[
  { marks: 95,  name: "student2"}, 
  { marks: 89,  name: "student3"}, 
  { marks: 72,  name: "student1"}
]  

Number Array Sort


const numberArray = [95,72,89];

const decendingResult = numberArray.sort(function(a, b){return b-a});
console.log(decendingResult); // output: [95, 89, 72]

const acedingResult = numberArray.sort(function(a, b){return a-b});
console.log(acedingResult); // output: [72, 89, 95]

String Array Sort


const stringArray = ["Amsterdam", "Paris", "London"];

const ascendingResult = stringArray.sort();
console.log(ascendingResult); // output: ["Amsterdam", "London", "Paris"]

console.log(ascendingResult.reverse()) //output: ["Paris", "London", "Amsterdam"]

Thanks for reading Blog!

Want to receive Tech Articles!

Get tech aricles directly in your inbox! Share your email with us and receive tech articles as instant as we publish!

Thanks for reading Blog!

KPIENG

KPITENG

DIGITAL TRANSFORMATION

Want to talk about your project?

  • INDUSTRY
  • E-Commerce & Shopping
  • Healthcared & Fitness
  • Banking & Finance
  • Education
  • Logistics & Distribution
  • Social Networking
  • Real Estate
  • Food & Restaurant
  • On-Demand Services
  • Media
  • IT & Telecom
  • Productivity

Want to talk about your project?

© 2021 KPITENG, all rights reserved