DEV Community

Amit Mondal
Amit Mondal

Posted on • Updated on

Handy Javascript Tricks ✨

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:

let num1 = 10;
let num2 = 20;
[num1, num2] = [num2, num1];
Enter fullscreen mode Exit fullscreen mode

2) Array Flatten:

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

// Flatten the array recursively:
array.flat(Infinity);
Enter fullscreen mode Exit fullscreen mode

3) When we want to use javascript object as a hash map(purely for storing data), you might want to create it as follows.

const dirtyMap = {};
const cleanMap = Object.create(null);

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

cleanMap.constructor    // undefined
Enter fullscreen mode Exit fullscreen mode

4) Removing Duplicate value and occurrence from an array:

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

5) Get unique values from an array:

const repeatedValues = [1,2,2,3,4,1,4,3,5,2];
const uniqueValues = [... new Set(repeatedValues)];
Enter fullscreen mode Exit fullscreen mode

6) Sorting in JavaScript:

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

7) Setting CSS using JavaScript in object form:

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

8) Using document.createDocumentFragment():
Creates a new empty DocumentFragment into which DOM nodes can be added to build an offscreen DOM tree.

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

9) Prettify stringified JSON output:

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

10) Convert an array to an object:

const fruits = ['banana', 'apple', 'orange', 'watermelon'];
const fruitsObj = { ...fruits };
Enter fullscreen mode Exit fullscreen mode

11) Fill array with data:

const numDummyArr = new Array(10).fill(1);
const strDummyArr = new Array(10).fill("a");
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)