42 Tips and Tricks to Write Faster, Better-Optimized JavaScript Code
Tags: javascript, beginners, codenewbie, webdev
Published: 2021-02-24 15:34:20


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

![](https://cdn-images-1.medium.com/max/900/0*xsBpJib2iOy6qSZm.jpg)

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.

#### 1. Using Underscore

#### `_.sortBy(collection, [iteratees=[_.identity]])`

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

#### 2. Using ES6 sort function

```
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 valuedata.sort(function (a, b) {  return a.value - b.value;});
```

#### 3. Using Lodash

```
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()_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/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

[**12 Methods for Finding an Item in an Array (and Array of Objects) in JavaScript**  
_I always used to prefer something like a newspaper which give enough information in a shorter span of time. Here, I…_medium.com](https://medium.com/javascript-in-plain-english/12-methods-for-finding-an-item-in-an-array-and-array-of-objects-in-javascript-484a1ba66324 "https://medium.com/javascript-in-plain-english/12-methods-for-finding-an-item-in-an-array-and-array-of-objects-in-javascript-484a1ba66324")[](https://medium.com/javascript-in-plain-english/12-methods-for-finding-an-item-in-an-array-and-array-of-objects-in-javascript-484a1ba66324)

### 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**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)**):**

> The `**_for...of_**` **statement** creates a loop iterating over [iterable objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol), including: built-in `[_String_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)`, `[_Array_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)`, array-like objects (e.g., `[_arguments_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)` or `[_NodeList_](https://developer.mozilla.org/en-US/docs/Web/API/NodeList)`), `[_TypedArray_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray)`, `[_Map_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)`, `[_Set_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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()**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/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 happened
```

```
return 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.

[**34 JavaScript Optimization Techniques to Know in 2021**  
_Optimize your JavaScript code using modern shorthand techniques, tips, and tricks_medium.com](https://medium.com/javascript-in-plain-english/34-javascript-optimization-techniques-to-know-in-2021-d561afdf73c3 "https://medium.com/javascript-in-plain-english/34-javascript-optimization-techniques-to-know-in-2021-d561afdf73c3")[](https://medium.com/javascript-in-plain-english/34-javascript-optimization-techniques-to-know-in-2021-d561afdf73c3)

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

**_Append Single Element at a specific index_**

```
//Append at index 2array.splice(2, 0,'newData');
```

```
//Append at index 5array[5] = 'newData';
```

**_Append Multiple Element at a specific index_**

```
//Append at index 2array.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

[**How to Remove Duplicates from an Array or Array of Objects in JavaScript**  
_I always used to prefer something like a newspaper which give enough information in a shorter span of time. Here, I…_medium.com](https://medium.com/javascript-in-plain-english/how-to-remove-duplicates-from-an-array-or-array-of-objects-in-javascript-9ab417cb9667 "https://medium.com/javascript-in-plain-english/how-to-remove-duplicates-from-an-array-or-array-of-objects-in-javascript-9ab417cb9667")[](https://medium.com/javascript-in-plain-english/how-to-remove-duplicates-from-an-array-or-array-of-objects-in-javascript-9ab417cb9667)

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

#### 1. includes

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

#### 2. index of

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.

[**21 Arrays and Object Tricks in JavaScript/TypeScript**  
_I always used to prefer something like a newspaper which give enough information in a shorter span of time. Here, I…_medium.com](https://medium.com/javascript-in-plain-english/21-arrays-and-object-tricks-in-javascript-typescript-9d41f5f4966c "https://medium.com/javascript-in-plain-english/21-arrays-and-object-tricks-in-javascript-typescript-9d41f5f4966c")[](https://medium.com/javascript-in-plain-english/21-arrays-and-object-tricks-in-javascript-typescript-9d41f5f4966c)

### 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:

#### 1. Sequential `for` loop:

```
var array = ["a","b"];var arrayLength = array.length;for (var i = 0; i < arrayLength; i++) {    console.log("value",array[i]);}
```

#### 2. Array.prototype.forEach

```
const data = ["a", "b", "c"];
```

```
data.forEach(function (item, index) {  console.log(item, index);});
```

#### 3. ES6 `for-of` statement

```
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

[**9 Methods for Sorting an Item in an Array (and Array of Objects) in JavaScript**  
_I always used to prefer something like a newspaper which give enough information in a shorter span of time. Here, I…_medium.com](https://medium.com/javascript-in-plain-english/9-methods-for-sorting-an-item-in-an-array-and-array-of-objects-in-javascript-8226f5d39590 "https://medium.com/javascript-in-plain-english/9-methods-for-sorting-an-item-in-an-array-and-array-of-objects-in-javascript-8226f5d39590")[](https://medium.com/javascript-in-plain-english/9-methods-for-sorting-an-item-in-an-array-and-array-of-objects-in-javascript-8226f5d39590)

### 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>
```

**22 Utility Functions To Ace Your JavaScript Coding Interview**

[**22 Utility Functions To Ace Your JavaScript Coding Interview**  
_JavaScript Coding Assessment Cheatsheet 2021_js.plainenglish.io](https://js.plainenglish.io/22-utility-functions-to-ace-your-javascript-coding-interview-21ca676ad70 "https://js.plainenglish.io/22-utility-functions-to-ace-your-javascript-coding-interview-21ca676ad70")[](https://js.plainenglish.io/22-utility-functions-to-ace-your-javascript-coding-interview-21ca676ad70)

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

There are several ways to achieve this function.

#### [1.jQuery](https://api.jquery.com/jQuery.isEmptyObject/):

```
jQuery.isEmptyObject({}); // true
```

#### [2. lodash](https://lodash.com/docs#isEmpty):

```
_.isEmpty({}); // true
```

#### [3. Underscore](https://underscorejs.org/#isEmpty):

```
_.isEmpty({}); // true
```

### 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);}
```

### 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Working_with_array-like_objects)).

```
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]
```

[**Continue reading**](https://js.plainenglish.io/42-tips-and-tricks-to-write-faster-better-optimized-javascript-code-3a82c53d051e)