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

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 merge two arrays in JavaScript and remove duplicate items?

We do play with arrays in day to day life and there are a lot of requirements where we need to combine arrays as well as need to remove duplicates.

Below are some approaches to achieve this.

1. Using Lodash

console.log(_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]));

2. Using Filter and Concat

var a = [1, 2, 3], b = [101, 2, 1, 10]

var c = a.concat(b)

var d = c.filter((item, pos) => c.indexOf(item) === pos)

3. Using Set

[...new Set([...array1 ,...array2])]; // => remove duplication

How do you clear the focus in javascript?

Focus… Focus… Yeah, this time we want to clear the focus from the specific element in the HTML. This can be achieved by the blur method.

if (document.activeElement instanceof HTMLElement)

document.activeElement.blur();

Binary to String in JavaScript

What if we have some binary code and we want to convert it into a string before using it in our code? It can be achieved using the fromCharCode method.

et binary = `1010011 1110100 1100001 1100011 1101011

1001111 1110110 1100101 1110010 1100110

1101100 1101111 1110111`;



let outputStr = binary.split(' ') //Split string in array of binary chars

.map(bin => String.fromCharCode(parseInt(bin, 2))) //Map every binary char to real char

.join(''); //Join the array back to a string



console.log(outputStr);

Shift strings Circular left and right in JavaScript

When we start practicing for the bigger companies this kind of javascript coding questions are common. Here is an example of shifting the string based on given values. It can be achieved using array slice methods.

function getShiftedString(s, leftShifts, rightShifts) {

// using `split('')` will result in certain unicode characters being separated incorrectly

// use Array.from instead:

const arr = Array.from(s);

const netLeftShifts = (leftShifts - rightShifts) % arr.length;

return [...arr.slice(netLeftShifts), ...arr.slice(0, netLeftShifts)]

.join('');

}



console.log([

getShiftedString('abc', 0, 0),

getShiftedString('abc', 1, 0),

getShiftedString('abc', 0, 1),

getShiftedString('abc', 1, 1),

getShiftedString('123456789', 0, 0),

getShiftedString('123456789', 1, 5),

getShiftedString('123456789', 5, 1),

'----',

getShiftedString('123456789', 9, 0),

getShiftedString('123456789', 10, 0),

getShiftedString('123456789', 0, 9),

getShiftedString('123456789', 0, 10),

getShiftedString("🐎👱❤", 0, 0),

getShiftedString("🐎👱❤", 1, 0),

]);

Regular expression to check for IP addresses JavaScript

Regex help us to check any specific string and validate for us? What if we want regex for the IP address.

Here is the cleanest way to validate an IP Address, Let’s break it down:

Fact: a valid IP Address is has 4 octets , each octet can be a number between 0 - 255

Breakdown of Regex that matches any value between 0 - 255

25[0-5] matches 250 - 255

matches 2[0-4][0-9] matches 200 - 249

matches 1[0-9][0-9] matches 100 - 199

matches [1-9][0-9]? matches 1 - 99

matches 0 matches 0

const octet = '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)';

Notes: When using new RegExp you should use \\. instead of \. since string will get escaped twice.

function isValidIP(str) {

const octet = '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)';

const regex = new RegExp(`^${octet}\\.${octet}\\.${octet}\\.${octet}$`);

return regex.test(str);

}

How to JSON stringify a JavaScript Date and preserve timezone

When we want to store any specific date formatted value to the JSON. It can be achieved using this function.

var replacer = function(key, value) {



if (this[key] instanceof Date) {

return this[key].toUTCString();

}



return value;

}



console.log(JSON.stringify(new Date(), replacer));

console.log(JSON.stringify({ myProperty: new Date()}, replacer));

JavaScript to check if a string is a valid number

We have seen a lot of solution to check the number is valid or not but What if want to check if a string is a valid number or not?

Here is the best approach.

function isNumeric(n) {

return !isNaN(parseFloat(n)) && isFinite(n);

}

Below are some good test cases:

console.log(isNumeric(12345678912345678912)); // true

console.log(isNumeric('2 ')); // true

console.log(isNumeric('-32.2 ')); // true

console.log(isNumeric(-32.2)); // true

console.log(isNumeric(undefined)); // false // the accepted answer fails at these tests:

console.log(isNumeric('')); // false

console.log(isNumeric(null)); // false

console.log(isNumeric([])); // false

Export a JSON Object to a text file

When we want to export the JSON Object to a text file, below is the cleanest approach I found till this date.

const filename = 'data.json';

const jsonStr = JSON.stringify(JsonExport);



let element = document.createElement('a');

element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(jsonStr));

element.setAttribute('download', filename);



element.style.display = 'none';

document.body.appendChild(element);



element.click();



document.body.removeChild(element);

Wrap long template literal line to multiline without creating a new line in the string

If you introduce a line continuation ( \ ) at the point of the new line in the literal, it won't create a new line on output:

const text = `a very long string that just continues\

and continues and continues`;

console.log(text);

How to copy text from a div to clipboard

When we want to copy text from a div to clipboard below is the simplest approach I found during my development.

function CopyToClipboard(containerid) {

if (window.getSelection) {

if (window.getSelection().empty) { // Chrome

window.getSelection().empty();

} else if (window.getSelection().removeAllRanges) { // Firefox

window.getSelection().removeAllRanges();

}

} else if (document.selection) { // IE?

document.selection.empty();

} if (document.selection) {

var range = document.body.createTextRange();

range.moveToElementText(document.getElementById(containerid));

range.select().createTextRange();

document.execCommand("copy");

} else if (window.getSelection) {

var range = document.createRange();

range.selectNode(document.getElementById(containerid));

window.getSelection().addRange(range);

document.execCommand("copy");

}

}

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?