DEV Community

Cover image for JavaScript Tips, Tricks and Best Practices
kpiteng
kpiteng

Posted on

JavaScript Tips, Tricks and Best Practices

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!

Take away -

  • 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

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

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

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"}
  ]
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

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"
}]
Enter fullscreen mode Exit fullscreen mode

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"
}]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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"}
]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading Article!

KPITENG | DIGITAL TRANSFORMATION
www.kpiteng.com | hello@kpiteng.com

Top comments (0)