9 Super Useful Tricks for JavaScript Developers

Useful Javascript tricks you might have missed.

Mike Chen
Bits and Pieces

--

As we all know, JavaScript has been changing rapidly. With the new ES2020, there are many awesome features introduced that you might want to checkout. To be honest, you can write code in many different ways. They might achieve the same goal, but some are shorter and much clearer. You can use some small tricks to make your code cleaner and clearer. Here is a list of useful tricks for JavaScript developers that will definitely help you one day.

Method Parameter Validation

JavaScript allows you to set default values for your parameters. Using this, we can implement a neat trick to validate your method parameters.

const isRequired = () => { throw new Error('param is required'); };const print = (num = isRequired()) => { console.log(`printing ${num}`) };print(2);//printing 2print()// errorprint(null)//printing null

Neat, isn’t it?

Format JSON Code

You would be quite familiar with JSON.stringify by now. But are you aware that you can format your output by using stringify ? It is quite simple actually.

The stringify method takes three inputs. The value , replacer , and space. The latter two are optional parameters. That is why we did not use them before. To indent our JSON, we must use the space parameter.

console.log(JSON.stringify({name:"John",Age:23},null,'\t'));>>> 
{
"name": "John",
"Age": 23
}

Here’s a React component I’ve published to Bit. Feel free to play with the stringify example.

Get Unique Values From An Array

Getting unique values from an array required us to use the filter method to filter out the repetitive values. But with the new Set native object, things are really smooth and easy.

let uniqueArray = [...new Set([1, 2, 3, 3,3,"school","school",'ball',false,false,true,true])];>>> [1, 2, 3, "school", "ball", false, true]

Removing Falsy Values From Arrays

There can be instances where you might want to remove falsy values from an array. Falsy values are values in JavaScript which evaluate to FALSE. There are only six falsy values in JavaScript and they are,

  • undefined
  • null
  • NaN
  • 0
  • “” (empty string)
  • false

The easiest way to filter out these falsy values is to use the below function.

myArray
.filter(Boolean);

If you want to make some modifications to your array and then filter the new array, you can try something like this. Keep in mind that the original myArray remains unchanged.

myArray
.map(item => {
// Do your changes and return the new item
})
.filter(Boolean);

Merge Several Objects Together

I have had several instances where I had the need to merge two or more classes, and this was my go-to approach.

const user = { 
name: 'John Ludwig',
gender: 'Male'
};
const college = {
primary: 'Mani Primary School',
secondary: 'Lass Secondary School'
};
const skills = {
programming: 'Extreme',
swimming: 'Average',
sleeping: 'Pro'
};
const summary = {...user, ...college, ...skills};

The three dots are also called the spread operator in JavaScript. You can read more of their uses over here.

Sort Number Arrays

JavaScript arrays come with a built-in sort method. This sort method converts the array elements into strings and performs a lexicographical sort on it by default. This can cause issues when sorting number arrays. Hence here is a simple solution to overcome this problem.

[0,10,4,9,123,54,1].sort((a,b) => a-b);>>> [0, 1, 4, 9, 10, 54, 123]

You are providing a function to compare two elements in the number array to the sort method. This function helps us the receive the correct output.

Disable Right Click

You might ever want to stop your users from right-clicking on your web page. Although this is very rare, there can be several instances where you would need this feature.

<body oncontextmenu="return false">
<div></div>
</body>

This simple snippet would disable right click for your users.

Destructuring with Aliases

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. Rather than sticking with the existing object variable, we can rename them to our own preference.

const object = { number: 10 };// Grabbing number
const { number } = object;
// Grabbing number and renaming it as otherNumber
const { number: otherNumber } = object;
console.log(otherNumber); //10

Get the Last Items in an Array

If you want to take the elements from the end of the array, you can use the slice method with negative integers.

let array = [0, 1, 2, 3, 4, 5, 6, 7] 
console.log(array.slice(-1));
>>>[7]
console.log(array.slice(-2));
>>>[6, 7]
console.log(array.slice(-3));
>>>[5, 6, 7]

Build with independent components, for speed and scale

Instead of building monolithic apps, build independent components first and compose them into features and applications. It makes development faster and helps teams build more consistent and scalable applications.

OSS Tools like Bit offer a great developer experience for building independent components and composing applications. Many teams start by building their Design Systems or Micro Frontends, through independent components.
Give it a try →

An independently source-controlled and shared “card” component. On the right => its dependency graph, auto-generated by Bit.

--

--