DEV Community

Atit Patel
Atit Patel

Posted on • Originally published at js.plainenglish.io

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

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

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' }];
Enter fullscreen mode Exit fullscreen mode
var sortedValues = _.sortBy( objs, 'val1' );
Enter fullscreen mode Exit fullscreen mode

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 }];
Enter fullscreen mode Exit fullscreen mode
// sort by valuedata.sort(function (a, b) {  return a.value - b.value;});
Enter fullscreen mode Exit fullscreen mode

3. Using Lodash

const sortedValues = _.sortBy(data, 'string');
Enter fullscreen mode Exit fullscreen mode

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

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

[_Number()_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number)Creates a new _Number_ value.

  1. Convert string to decimal
var string = 10.134.toFixed(2); // => '10.13'var num = Number(string); // => 10.13
Enter fullscreen mode Exit fullscreen mode

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

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" };
Enter fullscreen mode Exit fullscreen mode
Object.keys(data).forEach(function(key) {    console.log(key, obj[key]);});
Enter fullscreen mode Exit fullscreen mode

ES6 (for...of):

The **_for...of_** statement creates a loop iterating over iterable objects, 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]);}
Enter fullscreen mode Exit fullscreen mode

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

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

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

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
Enter fullscreen mode Exit fullscreen mode
// runtime error...navigation happened
Enter fullscreen mode Exit fullscreen mode
return false;});
Enter fullscreen mode Exit fullscreen mode

Example of preventDefault()

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

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

if (!!data) {    // Some code here}
Enter fullscreen mode Exit fullscreen mode

Or use type casting:

if (Boolean(data)) {    // Code here}
Enter fullscreen mode Exit fullscreen mode

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

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');
Enter fullscreen mode Exit fullscreen mode
//Append at index 5array[5] = 'newData';
Enter fullscreen mode Exit fullscreen mode

Append Multiple Element at a specific index

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

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

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

Using in operator

let data = "abc" in array;
Enter fullscreen mode Exit fullscreen mode

Using hasOwnProperty

let result = data.hasOwnProperty("abc")
Enter fullscreen mode Exit fullscreen mode

Accessing elements directly (brackets style)

let result = data["abc"] === undefined
Enter fullscreen mode Exit fullscreen mode

Accessing elements directly (object style)

let result = array.abc === undefined;
Enter fullscreen mode Exit fullscreen mode

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

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

3. Using Set

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

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";
Enter fullscreen mode Exit fullscreen mode
console.log(string.includes(val2));
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode
console.log(str.indexOf(substr) !== -1);
Enter fullscreen mode Exit fullscreen mode

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

11. How to replace all occurrences of a string?

  1. We can use ES6 to handle this.
str = str.replace(/test/g, '');
Enter fullscreen mode Exit fullscreen mode
  1. 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);
Enter fullscreen mode Exit fullscreen mode
  1. If you want a shallow copy

Object.assign({}, data)

  1. 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
Enter fullscreen mode Exit fullscreen mode
              !!0 === false!!parseInt("foo") === false // NaN is falsy              !!1 === true             !!-1 === true  // -1 is truthy          !!(1/0) === true  // Infinity is truthy
Enter fullscreen mode Exit fullscreen mode
             !!"" === false // empty string is falsy          !!"foo" === true  // non-empty string is truthy        !!"false" === true  // ...even if it contains a falsy value
Enter fullscreen mode Exit fullscreen mode
     !!window.foo === false // undefined is falsy           !!null === false // null is falsy
Enter fullscreen mode Exit fullscreen mode
             !!{} === true  // an (empty) object is truthy             !![] === true  // an (empty) array is truthy; 
Enter fullscreen mode Exit fullscreen mode

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

2. Array.prototype.forEach

const data = ["a", "b", "c"];
Enter fullscreen mode Exit fullscreen mode
data.forEach(function (item, index) {  console.log(item, index);});
Enter fullscreen mode Exit fullscreen mode

3. ES6 for-of statement

let data = ['a', 'b', 'c'];for (const a of data){    console.log(a);}
Enter fullscreen mode Exit fullscreen mode

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

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

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>
Enter fullscreen mode Exit fullscreen mode
<script>  function copy(text) {    window.prompt("To Copy Please do this: Ctrl+C, Enter", text);  }</script>
Enter fullscreen mode Exit fullscreen mode

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

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

There are several ways to achieve this function.

1.jQuery:

jQuery.isEmptyObject({}); // true
Enter fullscreen mode Exit fullscreen mode

2. lodash:

_.isEmpty({}); // true
Enter fullscreen mode Exit fullscreen mode

3. Underscore:

_.isEmpty({}); // true
Enter fullscreen mode Exit fullscreen mode

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;}
Enter fullscreen mode Exit fullscreen mode
  1. Using function we can call toUpperCase() method.
function makeUpperCase(val){    return val && val[0].toUpperCase() + val.slice(1);}
Enter fullscreen mode Exit fullscreen mode

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

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

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

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

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];
Enter fullscreen mode Exit fullscreen mode
Array.prototype.push.apply(array2, array1);
Enter fullscreen mode Exit fullscreen mode
console.log(array2); // [100, 2, 33, 45, 5]
Enter fullscreen mode Exit fullscreen mode

With ES6 it can be done using the spread operator.

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

Continue reading

Top comments (0)