42 Tips and Tricks to Write Faster, Better-Optimized JavaScript Code

Optimize your JavaScript code using modern techniques, tips, and tricks

Atit
Atit
Dec 24, 2020 · 17 min read
Image for post
Image for post

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 JavaScript 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 article can help you to prepare yourself for JavaScript interviews in 2021.

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

1. Sort an array of objects by string property value

It can be done in different ways.

Creates an array of elements, sorted in ascending order by the results of running each element in a collection thru each iteratee. This method performs a stable sort, that is, it preserves the original sort order of equal elements. The iteratees are invoked with one argument: (value).

var objs = [ 
{ val1: 'abc',val2: 'a' },
{ val1: 'cde', val2: 'b' },
{ val1: 'fgh', val2: 'c' }
];
var sortedValues = _.sortBy( objs, 'val1' );
var data = [
{ name: 'abc', value: 21 },
{ name: 'cde', value: 37 },
{ name: 'ee', value: 45 },
{ name: 'ff', value: -12 },
{ name: 'ab', value: 13 },
{ name: 'cs', value: 37 }
];
// sort by value
data.sort(function (a, b) {
return a.value - b.value;
});
const sortedValues = _.sortBy(data, 'string');

2. How to Round to at most 2 decimal places (only if necessary)

There are 3 different ways we can achieve this function.

Let’s understand some definitions before jumping to the solutions.

The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number.

The toFixed() method formats a number using fixed-point notation.

  1. Using ParseFloat
parseFloat("183.456").toFixed(2);

The Math.round() function returns the value of a number rounded to the nearest integer.

2. Using MathRound

Math.round( num * 100 + Number.EPSILON ) / 100

Number()Creates a new Number value.

3. Convert string to decimal

var string = 10.134.toFixed(2); // => '10.13'
var num = Number(string); // => 10.13

12 Methods for Finding an Item in an Array (and Array of Objects) in JavaScript

3. How do I loop through or enumerate a JavaScript Object?

Each ECMAScript version comp up with a different way to enumerate the Objects. Let’s check this out.

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.

The forEach() method executes a provided function once for each array element.

ES5 (Object.keys() and forEach)

var data = { val1: "abc", val2: "cde" };Object.keys(data).forEach(function(key) {
console.log(key, obj[key]);
});

ES6 (for...of):

The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.

for (const key of Object.keys(data)) {
console.log(key, obj[key]);
}

ES8 Object.entries()

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop.

Object.entries(data).forEach(
([key, value]) => console.log(key, value)
);

We can combine for...of, destructuring, and Object.entries:

for (const [key, value] of Object.entries(data)) {
console.log(key, value);
}

4. What is the difference between event.preventDefault() and return false

with return false, there is a chance that other functions are getting executed which is specifically written inside the click while preventDefault won’t allow executing anything.

$('a').click(function (e) {
// logic
// runtime error...navigation happenedreturn false;
});

Example of preventDefault()

$('a').click(function (e) {
e.preventDefault();
// logic// runtime error, naviagation will not happen
});

5. How can I check for an empty/undefined/null string in JavaScript?

if (!!data) {
// Some code here
}

Or use type casting:

if (Boolean(data)) {
// Code here
}

Both do the same function. Typecast the variable to Boolean, where str is a variable.
It returns false for null, undefined, 0, 000, "", false.
It returns true for string "0" and whitespace " ".

If you are looking to Optimize your JavaScript code using modern shorthand techniques, tips, and tricks check out this article.

6. How to insert an item into an array at a specific index (JavaScript)?

Append Single Element at a specific index

//Append at index 2
array.splice(2, 0,'newData');
//Append at index 5
array[5] = 'newData';

Append Multiple Element at a specific index

//Append at index 2
array.splice(2, 0,'data1', 'data2', 'data3');

7. How to Get the current URL with JavaScript?

Use windows function:window.location.href

How to Remove Duplicates from an Array or Array of Objects in JavaScript

8. Checking if a key exists in a JavaScript object?

Using in operator

let data = "abc" in array;

Using hasOwnProperty

let result = data.hasOwnProperty("abc")

Accessing elements directly (brackets style)

let result = data["abc"] === undefined

Accessing elements directly (object style)

let result = array.abc === undefined;

9. 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([10, 4, 5], [134, 26, 19, 10], [6, 1]));

2. Using Filter and Concat

let a = [56, 43, 3], b = [11, 43, 56, 12]
let c = a.concat(b)
let d = c.filter((val, pos) => c.indexOf(val) === pos)

3. Using Set

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

10. How to check whether a string contains a substring in JavaScript?

We can use the following two methods to achieve this function.

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

const val1 = "atitpatel";
const val2 = "patel";
console.log(string.includes(val2));

The indexOf() the method returns the first index at which a given element can be found in the array, or -1 if it is not present.

var str = "atitpatel";
var substr = "patel";
console.log(str.indexOf(substr) !== -1);

If you are looking for array and object-related tips please check out this article.

11. How to replace all occurrences of a string?

  1. We can use ES6 to handle this.
str = str.replace(/test/g, '');

2. We can use Regex.

let find = 'ab';let re = new RegExp(find, '');let str = find.replace(re, 'cd');console.log(str);

12. How to correctly clone a JavaScript object?

  1. Using ES6
var val1 = {data: "value"};
var val2= Object.assign({}, val1);

2. If you want a shallow copy

Object.assign({}, data)

3. For a deep copy

JSON.parse(JSON.stringify(data))

13. What is the !! (not not) an operator in JavaScript?

!! converts the value to the right of it to its equivalent boolean value.

!!false === false
!!true === true
!!0 === false
!!parseInt("foo") === false // NaN is falsy
!!1 === true
!!-1 === true // -1 is truthy
!!(1/0) === true // Infinity is truthy
!!"" === false // empty string is falsy
!!"foo" === true // non-empty string is truthy
!!"false" === true // ...even if it contains a falsy value
!!window.foo === false // undefined is falsy
!!null === false // null is falsy
!!{} === true // an (empty) object is truthy
!![] === true // an (empty) array is truthy;

14. How to Loop through an array in JavaScript

we have several options:

var array = ["a","b"];
var arrayLength = array.length;
for (var i = 0; i < arrayLength; i++) {
console.log("value",array[i]);
}
const data = ["a", "b", "c"];data.forEach(function (item, index) {
console.log(item, index);
});
let data = ['a', 'b', 'c'];
for (const a of data){
console.log(a);
}

9 Methods for Sorting an Item in an Array (and Array of Objects) in JavaScript

15. How do I copy to the clipboard in JavaScript?

We can prompt the user to click and enter by doing this:

function copy(text) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}

Now the clipboard copy operation is SAFE because a user has clicked on the prompt.

<button id="data" onclick="copy(document.getElementById('data').innerHTML)">Copy here</button><script>
function copy(text) {
window.prompt("To Copy Please do this: Ctrl+C, Enter", text);
}
</script>

Recently, I was trying to prepare myself for the upcoming interviews and it was a bit tough to search in google and open link and see same questions each and every time so I thought of sharing what I have found and what is most common questions someone should know if they are preparing for an interview.

Below are the most common interview questions asked in Latest Angular Developer Interviews. These Angular Interview questions and answers help to prepare for Angular developer interviews from junior to senior levels. Moreover, this article covers the basics to advance angular interview questions which you must prepare in 2021.

16. How do I test for an empty JavaScript object?

There are several ways to achieve this function.

jQuery.isEmptyObject({}); // true
_.isEmpty({}); // true
_.isEmpty({}); // true

How to Handle Multiple Service Calls Inside a Loop

17. How do I make the first letter of a string uppercase in JavaScript?

We can either update the CSS which has text-transform property.

  1. In CSS:
p:first {
text-transform:capitalize;
}

2. Using function we can call toUpperCase() method.

function makeUpperCase(val)
{
return val && val[0].toUpperCase() + val.slice(1);
}

If you would like to get up to date yourself with the latest features of JavaScript versions check out this article.

18. How can I change an element’s class with JavaScript?

There are a lot of requirements where we need to change some color or CSS based on conditions.

How it can be done in JavaScript?

To change all classes for an element:

To replace all existing classes with one or more new classes, set the className attribute:

document.getElementById("test").className = "newclass";

To add an additional class to an element:

To add a class to an element, without removing/affecting existing values, append a space and the new class name, like so:

document.getElementById("test").className += " newClass";

To remove a class from an element:

To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:

document.getElementById("test").className =
document.getElementById("test").className.replace
( /(?:^|\s)newClass(?!\S)/g , '' )

19. Is it possible to apply CSS to half of a character?

We do see some fancy word art where the half of the character have different color while other half have different color. How we can achieve something like this in CSS?

Below is the example to make apply CSS for half character.

h1 {
display: inline-block;
margin: 0; /* for demo snippet */
line-height: 1em; /* for demo snippet */
font-family: helvetica, arial, sans-serif;
font-weight: bold;
font-size: 300px;
background: linear-gradient(to right, #7db9e8 50%,#1e5799 50%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
<h1>XYZ</h1>

20. How to append something to an array?

In the older JavaScript version, it was done by using the apply method.

The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).

let array1 = [33, 45, 5];
let array2 = [100, 2];
Array.prototype.push.apply(array2, array1);console.log(array2); // [100, 2, 33, 45, 5]

With ES6 it can be done using the spread operator.


let array1 = [11, 42, 53];
let array2 = [1, 2];
array2.push(...array1);console.log(array2); // [11, 2, 3, 42, 53]

21. How to check if an object is an array?

When we would like to check that if the object is array or not we can follow the below options.

let arr = [10,20,30,40,50];

Javascript (new and older browsers):

function isArray(arr) {
return arr.constructor.toString().indexOf("Array") > -1;
}
function isArray(arr) {
return arr instanceof Array;
}
function isArray(arr) {
return Object.prototype.toString.call(arr) === '[object Array]';
}

then call it like this:

isArray(arr);

JavaScript (IE9+, Ch5+, FF4+, Saf5+, Opera10.5+)

Array.isArray(arr);

Underscore and Lodash:

_.isArray(arr);

22. How to detect an undefined object property?

When we would like to check the specific property of an object is undefined we can directly check using the if condition with === operator.

if(data.prop === undefined) {
alert("it is: `undefined`");
}

To check if an object does not actually have such a property, and will therefore return undefined by default when you try and access it:

if(!o.hasOwnProperty('prop')) {
alert("not exisiting);
}

To check if the value associated with an identifier is the special value undefined, or if that identifier has not been declared.

if(typeof variable === 'undefined') {
alert('variable is `undefined`, or it is not declared');
}

23. How can I convert a string to a boolean in JavaScript?

There are several methods to convert a string to a boolean in JavaScript.

Using the test method

var stringValue = "true";
var boolValue = (/true/i).test(stringValue) //returns true

Using comparison operator

var val = "true";
var boolValue = (val =="true"); //returns true

Using JSON.parse

var val = "true";
var boolValue = JSON.parse(val); //returns true

Using ternary operator

var val = “true”;
var boolValue = val.toLowerCase() == ‘true’ ? true : false; //returns true

Using switch-case

var val = "true";
var boolValue = getBoolean(val); //returns true
function getBoolean(value){
switch(value){
case true:
case "true":
case 1:
case "1":
case "on":
case "yes":
return true;
default:
return false;
}
}

24. How can I get query string values in JavaScript?

This is the most common usage when we deal with the URL parameters and want to extract the information from the URL.

Below are some methods from which we can get the string values.

ES2015 (ES6): creating a method to achieve this function

getQueryStringParams = query => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split('&')
.reduce((params, param) => {
let [key, value] = param.split('=');
params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
return params;
}, {}
)
: {}
};

URLSearchParams use the inbuilt method from location

You can use it on location:

let params = new URLSearchParams(location.search);let params = (new URL(location)).searchParams;
let url = new URL('https://abc.com?val1=1&val2=2');
let params = new URLSearchParams(url.search);

we can get params also using a shorthand .searchParams property on the URL object, like this:

let params = new URL('https://abc.com?val1=1&val2=2').searchParams;
params.get('val1'); // "1"
params.get('val2'); // "2"

25. 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

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

2. Using underscore

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

26. 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));

27. 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);

28. How to detect if the user changes the 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")
}
})

29. 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))

30. 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() // 1/06/2021new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // 01/06/2021 (month and day with two digits)new Date().toLocaleDateString('en-ZA'); // 2020/01/06(year/month/day) notice the different localenew Date().toLocaleDateString('en-CA'); // 2021-01-06 (year-month-day) notice the different localenew 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');

31. 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)); // "cFg3Upv2cE5cK8Xd7hHwWp"
console.log(generateUID(5)); // "CAGkP"

32. 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));

33. 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() it to retrieve values and then array.reduce() compose a new object:

const data = [{
prop_name: 'test1',
prop_age: 45,
prop_email: 'test1@test.com',
},
{
prop_name: 'test2',
prop_age: 41,
prop_email: 'test2@test.com',
},
{
prop_name: 'test3',
prop_age: 45,
prop_email: 'test3@test.com',
},
];
const newKey = [
'firstname',
'age',
'email'
];
let resultData = data.map(obj =>
Object.values(obj).reduce((acc, cur, i) => {
acc[newKey[i]] = cur;
return acc;
}, {}));
console.log(resultData);

34. 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();

35. 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.

let binary = `1010011 1110100 1100001 1100011 1101011 
1001111 1110110 1100101 1110010 1100110
1101100 1101111 1110111`;
let newData = binary.split(' ') //Split string in array of binary chars
.map(bin => String.fromCharCode(parseInt(bin, 2))) //Map every binary char to real character
.join(''); //Join the array back to a string
console.log(newData);

36. 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),
]);

37. 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. I liked Mahdi Pedram solution here to achieve this.

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
  • 2[0-4][0-9] matches 200 - 249
  • 1[0-9][0-9] matches 100 - 199
  • [1-9][0-9]? matches 1 - 99
  • 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);
}

38. 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 changeValue = function(key, value) {   if (this[key] instanceof Date) {
return this[key].toUTCString();
}

return value;
}
console.log(JSON.stringify(new Date(), changeValue));
console.log(JSON.stringify({ myProperty: new Date()}, changeValue));

39. 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(123456898898912345678912)); // true
console.log(isNumeric('2 ')); // true
console.log(isNumeric('-42.2 ')); // true
console.log(isNumeric(-562.2)); // true
console.log(isNumeric(undefined)); // false
console.log(isNumeric('')); // false
console.log(isNumeric(null)); // false
console.log(isNumeric([])); // false

40. 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 from NutCracker answer.

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);

41. 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 = `abc abc abc abc abc abc abc\
and abc and abc`;
console.log(text);

42. 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 from StackOverflow romin21 answer.

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?

Top 100 Questions You Must Prepare For Your Next Angular Interview

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store