10 Super Useful Tricks for JavaScript Developers

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

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.


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

查看所有标签

猜你喜欢:

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

机器学习系统设计

机器学习系统设计

[德] Willi Richert、Luis Pedro Coelho / 刘峰 / 人民邮电出版社 / 2014-7-1 / CNY 49.00

如今,机器学习正在互联网上下掀起热潮,而Python则是非常适合开发机器学习系统的一门优秀语言。作为动态语言,它支持快速探索和实验,并且针对Python的机器学习算法库的数量也与日俱增。本书最大的特色,就是结合实例分析教会读者如何通过机器学习解决实际问题。 本书将向读者展示如何从原始数据中发现模式,首先从Python与机器学习的关系讲起,再介绍一些库,然后就开始基于数据集进行比较正式的项目开......一起来看看 《机器学习系统设计》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具