Handy Javascript Tricks ✨
Tags: javascript, webdev
Published: 2020-05-09 20:22:18

In this article 📝, we will look at some JavaScript tricks that can be handy.

While many of these tricks are handy in any context, a few of them may be better suited for code golf than production-level code, where clarity is often more important than concision. You are the best judge of that! 😄

In no particular order, here are a few neat ways to write concise and more performant code.

Copy and paste the code snippets in your browser's console to see the output.

1) Swap two values:
```js
let num1 = 10;
let num2 = 20;
[num1, num2] = [num2, num1];
```

2) Array Flatten:
```js
// Flatten one level:
const array = [1, [2, [3]]];
array.flat();

// Flatten the array recursively:
array.flat(Infinity);
```

3) When we want to use javascript object as a hash map(purely for storing data), you might want to create it as follows.
```js
const dirtyMap = {};
const cleanMap = Object.create(null);

dirtyMap.constructor    // function Object() { [native code] }

cleanMap.constructor    // undefined
```

4) Removing Duplicate value and occurrence from an array:
```js
// Time complexity O(n²)
const duplicateValues = [1,2,2,3,6,4,1,4,3,5,2];
duplicateValues.filter((num,i,arr) => arr.indexOf(num) === arr.lastIndexOf(num))

// Time complexity O(n)
const duplicateValues = [1,2,2,3,63,6,4,1,4,3,5,2];
const counter = {}

duplicateValues.forEach(num => {
  if (counter[num]){
    counter[num] += 1
  } else {
    counter[num] = 1
  }
})

Object.keys(counter).forEach(key => {
    if (counter[key] !== 1) {
        delete counter[key]
    }
});

const removedDuplicates = Object.keys(counter);
```

5) Get unique values from an array:
```js
const repeatedValues = [1,2,2,3,4,1,4,3,5,2];
const uniqueValues = [... new Set(repeatedValues)];
```

6) Sorting in JavaScript:
```js
// Sort number in ascending order
unsortedArr = [5,6,2,4,1,8,0,-3,-6,-1,45]
unsortedArr.sort((num1, num2) => num1 - num2);

// Sort number in descending order
unsortedArr = [5,6,2,4,1,8,0,-3,-6,-1,45]
unsortedArr.sort((num1, num2) => num2 - num1);

// Sort string in ascending order
unsortedArr = ['Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter']
unsortedArr.sort();

// Sort string in descending order
unsortedArr = ['Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter']
unsortedArr.sort().reverse();

// Sort string length in ascending order
unsortedArr = ['Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter']
unsortedArr.sort((str1, str2) => str1.length - str2.length);

// Sort string length in descending order
unsortedArr = ['Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter']
unsortedArr.sort((str1, str2) => str1.length - str2.length).reverse();

// Using localeCompare() enables case-insensitive sorting for an array in ascending order.
unsortedArr = ['réservé', 'Premier', 'Cliché', 'communiqué', 'café', 'Adieu'];
unsortedArr.sort( (a, b) => a.localeCompare(b, 'fr', {ignorePunctuation: true}));
```

7) Setting CSS using JavaScript in object form:
```js
const event_type = document.createElement('span');
Object.assign(event_type.style, {
   fontWeight: 'bold',
   display: 'inline-block',
   width: '128px',
   paddingLeft: '10px',
   paddingRight: '10px',
   color: eventName === 'text-change' ? '#22d' : '#8af', //conditionally assign value
 });
```

8) Using `document.createDocumentFragment()`:
Creates a new empty DocumentFragment into which DOM nodes can be added to build an offscreen DOM tree.
```js
// Normal Approach:
for (let i = 0; i < 1000; i++) {
  const paragraph = document.createElement('p');
  document.body.appendChild(paragraph )
}

// Optimized Approach:
const fragment = document.createDocumentFragment();

for (let i = 0; i < 1000; i++) {
  const p = document.createElement('p');
  fragment.appendChild(p)
}
document.body.appendChild(fragment)
```

9) Prettify stringified JSON output:
```js
const person = {
  firstName: 'Amit',
  lastName: 'Mondal',
  gender: 'Male',
  interests: ['Coding', 'Gaming', 'Solving Rubix Cube']
};

const normalStringify = JSON.stringify(person);
const prettyStringify = JSON.stringify(person, null, 2);
// OR
const prettyStringify = JSON.stringify(person, null, '\t');

console.log(normalStringify);
console.log(prettyStringify);
```

10) Convert an array to an object:
```js
const fruits = ['banana', 'apple', 'orange', 'watermelon'];
const fruitsObj = { ...fruits };
```

11) Fill array with data:
```js
const numDummyArr = new Array(10).fill(1);
const strDummyArr = new Array(10).fill("a");
```

Might add some more in the future.
Thank you for your time⌛.