10 Super Useful Tricks for JavaScript Developers
Useful Javascript tricks you might have missed.
As we all know, JavaScript has been changing rapidly. With the new ES2020, there are many awesome features introduced that you might want to check out. 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 2
print() // error
print(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. Thevalue
, 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 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 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 a 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]
Wait Until Promises Are Complete
There might be instances where you will need to wait for several promises to be over. We can use Promise.all
to run our promises in parallel.
Note: Promises will run concurrently in a single-core CPU and will run in parallel in a multi-core CPU. Its main task is to wait until all the promises that are passed to it are resolved.
const PromiseArray = [
Promise.resolve(100),
Promise.reject(null),
Promise.resolve("Data release"),
Promise.reject(new Error('Something went wrong'))
];
Promise.all(PromiseArray)
.then(data => console.log('all resolved! here are the resolve values:', data))
.catch(err => console.log('got rejected! reason:', err))
One main thing to note about Promise.all
is that the method throws an error when one of the promises reject. This would mean that your code will not wait until all your promises are complete.
If you want to wait until all your promises are complete, regardless of whether they get rejected or resolved, you can use the Promise.allSettled
. This method is in the finalized version of ES2020.
const PromiseArray = [
Promise.resolve(100),
Promise.reject(null),
Promise.resolve("Data release"),
Promise.reject(new Error('Something went wrong'))
];
Promise.allSettled(PromiseArray).then(res => {
console.log(res);
}).catch(err => console.log(err));
//[
//{status: "fulfilled", value: 100},
//{status: "rejected", reason: null},
//{status: "fulfilled", value: "Data release"},
//{status: "rejected", reason: Error: Something went wrong ...}
//]
Even though some of the promises are rejected, Promise.allSettled
returns the results from all your promises.
Publish and Reuse React Components with Bit
Bit makes it easy to publish reusable React components from any codebase to Bit’s component hub.
Need to update a published component? bit import
it into your project, change it, and push it back with a bumped version.
Share components with your team to maximize code reuse, speed up delivery, and build apps that scale.
Example: exploring React components published on Bit.dev
Related Stories
- Building a React Design System Build a reusable React design system to speed and standardize web application development.blog.bitsrc.io
- Building with React for All Platforms: Top Frameworks and Tools 5 recommended frameworks and tools that will help you use React to build for all platforms.blog.bitsrc.io
- Code Principles Every Programmer Should Follow YAGNI, Law of Demeter, Single Responsibility and other useful principles for better coding.blog.bitsrc.io
That’s it for this article. If you have any other tricks that might be helpful, please do mention them in the comments.
Happy Coding!!
Resources