JavaScript Tips, Tricks, and Best Practices
Tags: Front End Development, Javascript Tips, JavaScript, Web Development, Programming

JavaScript Tips, Tricks, and Best Practices

I always used to prefer something like a newspaper which give enough information in a shorter span of time. Here, I create tips for day to day Frontend development.

You might be doing angular development for a long time but sometimes you might be not updated with the newest features which can solve your issues without doing or writing some extra codes. This can cover some frequently asked Angular topics in interviews.

Here I am coming with a new series to cover some tips which helped me in my day-to-day coding.

How to get the length of a JavaScript object?

In most of the cases we do check the length of the array but what if want to check the length of objects? The following two methods are the best approaches to get the length of the Object.

1. Using Es6 feature

var size = Object.keys(data).length;

2. Using underscore

_.size({val1 : 1, val2 : 2, val3 : 3});

How to reverse a string that contains complicated emojis?

When we do more coding or attend some coding challenges, this is the most common question among them.

We can use lodash feature to achieve this challenge.

function reverse(txt) { return _.split(txt, '').reverse().join(''); } const data = 'abc abc👩‍🦰👩‍👩‍👦‍👦';

console.log(reverse(data));

How can I convert a string to an array of objects in JavaScript?

This type of scenario comes when we get some data from third-party APIs where we don't have control. How we can convert a string to an array of objects to use in our application? Below is the easiest approach to achieve this result.

const

str = 'Option 1|false|Option 2|false|Option 3|false|Option 4|true',

data = [];



for (let i = 0, a= str.split('|'); i < a.length; i += 2) {

const

option = a[i],

value = JSON.parse(a[i + 1]);

data.push({ option, value });

}



console.log(data);

How to detect if the user changes tab in JavaScript?

This can be achieved by the latest event listener feature supported by JavaScript.

Below is the solution to handle the state of the tab.

document.addEventListener("visibilitychange", event => {

if (document.visibilityState == "visible") {

console.log("activated")

} else {

console.log("inactivated")

}

})



How to sum a property value from an array of objects?

When we have an array of objects which contain some number which we want to get sum below is the solution with reduce.

const data = [

{ val1: 'abc', val2: 50 },

{ val1: 'abc', val2: 50 },

{ val1: 'cde', val2: 75 },

{ val1: 'hji', val2: 35 },

{ val1: 'bbc', val2: 25 },

]; console.log(data.reduce((n, {val2}) => n + val2, 0))

How to Format JavaScript date?

When we come to formatting the date, it’s more headache as we do have different requirements according to the needs. How we can achieve everyone's needs? Below are the most common methods used widely to format date in JavaScript.

1. You can use the native .toLocaleDateString()

Examples:

new Date().toLocaleDateString() // 8/19/2020 new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // 10/25/2020 (month and day with two digits) new Date().toLocaleDateString('en-ZA'); // 2020/10/25(year/month/day) notice the different locale new Date().toLocaleDateString('en-CA'); // 2020-10-25 (year-month-day) notice the different locale new Date().toLocaleString("en-US", {timeZone: "America/New_York"}); // 10/125/2020, 7:29:51 PM. (date and time in a specific timezone) new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"}); // 07 (just the hour)

2. We can use the moment.js

var now = new Date();

var dateString = moment(now).format('YYYY-MM-DD');



var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:mm:ss'); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"

How to Generate random string/characters in JavaScript?

There are a lot of times we need to send some random unique IDs to the backend. There are thousands of solutions to achieve this function but the following one I loved the most.

Generate a secure random alphanumeric Base-62 string:

function generateUID(length)

{

return window.btoa(Array.from(window.crypto.getRandomValues(new Uint8Array(length * 2))).map((b) => String.fromCharCode(b)).join("")).replace(/[+/]/g, "").substring(0, length);

} console.log(generateUID(22)); // "cFg3Upv2cE8cK8Xd7hHwWp"

console.log(generateUID(5)); // "CQGkP"

How to execute API calls after entering 3 characters in the field?

This is most commonly used when we want to search for a username or some value that already exists but to avoid call all the time we want to wait for the user to type certain characters before calling API.

This can be achieved using distinctUntilChanged And you can use the filter in the pipe

this.service.getData(data)

.pipe(

filter(_ => data.length === 3),

distinctUntilChanged()

).subscribe(rs => console.log(rs));

How to rename object keys inside an array?

Sometimes we need to change the keys to manipulate data. This is one of the efficient ways to rename the object keys inside an array.

You can use Object.values() to retrieve values and then array.reduce() to compose a new object:



prop_name: 'Negan',

prop_age: 45,

prop_weapon: 'Bat',

prop_email: '

prop_city: 'Washington'

},

{

prop_name: 'Daryl',

prop_age: 41,

prop_weapon: 'Crossbow',

prop_email: '

prop_city: 'Atlanta'

},

{

prop_name: 'Rick',

prop_age: 45,

prop_weapon: 'Magnum 357',

prop_email: '

prop_city: 'King County'

},

];

const newKeys = [

'firstname',

'age',

'weapon',

'email',

'city'

];

let result = customers.map(obj =>

Object.values(obj).reduce((acc, cur, i) => {

acc[newKeys[i]] = cur;

return acc;

}, {}));

console.log(result); const customers = [{prop_name: 'Negan',prop_age: 45,prop_weapon: 'Bat',prop_email: ' negan@sanctuary.com ',prop_city: 'Washington'},prop_name: 'Daryl',prop_age: 41,prop_weapon: 'Crossbow',prop_email: ' daryl.dixon@kickass.com ',prop_city: 'Atlanta'},prop_name: 'Rick',prop_age: 45,prop_weapon: 'Magnum 357',prop_email: ' rick@alexandria.com ',prop_city: 'King County'},];const newKeys = ['firstname','age','weapon','email','city'];let result = customers.map(obj =>Object.values(obj).reduce((acc, cur, i) => {acc[newKeys[i]] = cur;return acc;}, {}));console.log(result);

References:

Are you preparing for interviews? Here are frequently asked interview questions in Angular. It covers the Latest interview questions for Angular and Frontend development. Let’s check how many of these questions you can answer?