10 Super Useful Tricks for JavaScript Developers

栏目: IT技术 · 发布时间: 4年前

10 Super Useful Tricks for JavaScript Developers

Useful Javascript tricks you might have missed.

10 Super Useful Tricks for JavaScript Developers

Jun 2 ·5min read

10 Super Useful Tricks for JavaScript Developers

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
}

I’ve used a React component that I’ve published to Bit to demonstrate using the stringify arguments.

10 Super Useful Tricks for JavaScript Developers
https://bit.dev/eden/stringify-components/display-results

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
“”
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 splice 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 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 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.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

高中数学公式定律及要点透析

高中数学公式定律及要点透析

牛胜玉 编 / 2011-2 / 9.80元

《PASS绿卡图书:高中数学公式定律及要点透析(人教A版)(必修+选修)(第9次修订)》精选例句:时尚鲜活例句,再现巩固单词;延伸拓展:搭配用法辨析,提升运用能力;真题例句:精选真题例句,紧密联系高考。便于携带:三年教材词汇,方便随时记忆;附赠录音:用耳朵记单词,让学习零空隙。一起来看看 《高中数学公式定律及要点透析》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具