Common techniques and few little-known features of JS

Keywords: Javascript Attribute Programming github

Author: Euel Duran
Source: Dev
Translator: Front-end wit

Ali Yun has been doing activities recently, as low as 2 fold, and is interested to see:
https://promotion.aliyun.com/...

JS is a fast-growing language. Because of this, there are some new features and functions that we can't know in time.In this article, we will focus on some features that few people know and some common techniques.

Get query string parameters

URLSearchParams is a query string whose interface defines some useful ways to handle URLs. It's been around for several years, but it's not popular among developers. It's a little surprising. Let's see how to use it

var paramsString = "q=URLUtils.searchParams&topic=api";
var searchParams = new URLSearchParams(paramsString);

//Iterate the search parameters.
for (let p of searchParams) {
  console.log(p);
}

searchParams.has("topic") === true; // true
searchParams.get("topic") === "api"; // true
searchParams.getAll("topic"); // ["api"]
searchParams.get("foo") === null; // true
searchParams.append("topic", "webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
searchParams.set("topic", "More webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
searchParams.delete("topic");
searchParams.toString(); // "q=URLUtils.searchParams"

Create a unique list of elements using Set objects

Creating unique lists with JS is a common task, usually through filters or for loops, but there is another way to do this with Set objects.

const list = [1, 2, 3, 5, 2, 5, 7];
const uniqueList = [...new Set(list)];

Pass the original value array to the Set object, which creates a unique set of values, then uses the expansion operator syntax and the array literal quantity to turn them back into the array.

Convert the original value list to another type

Sometimes data processed in the background or DOM is not the type we need, as I've seen when working with the properties of datasets.Suppose you have the following list:

const naiveList = ['1500', '1350', '4580'];

To calculate the sum of all elements in an array, in JS, the addition of strings splits two strings together, like'1'+'2' which will be joined to'12'. Usually, to solve this problem, we will use the parseInt function, but there is another way; we can convert elements in an array to the basic requiredtype

const castedList = naiveList.map(Number);
console.log(castedList) // [1500, 1350, 4580]

The castedList now contains values of the correct Number type.

Flat nested array

With the rise of concepts such as single-page application architecture (such as Redux) and front-end data normalization, this "data normalization" trend sometimes means that the IDs of all elements need to be placed at the same level.

Suppose you have the following list, let's flatten it:

const nestedList = [133, 235, 515, [513, 15]];
const flattenList = nestedList.flat();
console.log(flattenList) //  [133, 235, 515, 513, 15]

Like this, our id array is flattened.

Use object.Freeze to avoid objects being altered

With the rise of functional x programming, data immutability has become more and more important, so we can use Object.freeze to prevent objects from being changed.

const immutableObject = {
    name: 'Front end wit',
    url: 'https://Xiaozhi 66.com'
};
Object.freeze(immutableObject);

immutableObject.wechat = 'qq449245884'
immutableObject.name = 'Wang Dazhi' 
console.log(immutableObject) // {name:'Smart Front', url:'https://Smart 66.com'}

Create controlled objects using Object.seal

The Object.seal() method encloses an object, prevents new attributes from being added and marks all existing attributes as unconfigurable.The value of the current property can be changed as long as it is writable, Object.freeze can do nothing, and Object.seal() can change the value of the property.

const controlledObject = {
    name: 'Front end wit'
};
Object.seal(controlledObject);
controlledObject.name = 'Wang Daye';
controlledObject.hero = 'Hero';  

console.log(controlledObject) // {name:'wang daye'}

Ensure Array Value

With grid, the original data needs to be recreated, and the column lengths of each row may not match. To ensure that the lengths between mismatched rows are equal, you can use the Array.fill method.

let array = Array(5).fill('');
console.log(array); // outputs (5) ["", "", "", "", ""]

Method of array map (without using Array.Map)

Another way to implement array maps is to not use Array.map.

Array.from also accepts the second parameter, which acts like an array's map method, handling each element and putting the processed value into the returned array.The following:

const cities = [
    { name: 'Paris', visited: 'no' },
    { name: 'Lyon', visited: 'no' },
    { name: 'Marseille', visited: 'yes' },
    { name: 'Rome', visited: 'yes' },
    { name: 'Milan', visited: 'no' },
    { name: 'Palermo', visited: 'yes' },
    { name: 'Genoa', visited: 'yes' },
    { name: 'Berlin', visited: 'no' },
    { name: 'Hamburg', visited: 'yes' },
    { name: 'New York', visited: 'yes' }
];

const cityNames = Array.from(cities, ({ name}) => name);
console.log(cityNames);
// outputs ["Paris", "Lyon", "Marseille", 
// "Rome", "Milan", "Palermo", "Genoa", "Berlin", "Hamburg", "New York"]

Conditional Object Properties

Instead of creating two different objects based on one condition, you can use the expansion operator symbol to handle them.

nst getUser = (emailIncluded) => {
  return {
    name: 'John',
    surname: 'Doe',
    ...emailIncluded && { email : 'john@doe.com' }
  }
}

const user = getUser(true);
console.log(user); // outputs { name: "John", surname: "Doe", email: "john@doe.com" }

const userWithoutEmail = getUser(false);
console.log(userWithoutEmail); // outputs { name: "John", surname: "Doe" }

Dynamic Property Name

Earlier, if the attribute name needed to be dynamic, we had to first declare an object, then assign an attribute.These days are over, and with the ES6 feature, we can do that.

const dynamic = 'email';
let user = {
    name: 'John',
    [dynamic]: 'john@doe.com'
}
console.log(user); // outputs { name: "John", email: "john@doe.com" }

BUGs that may exist after code deployment are not known in real time. In order to solve these BUGs afterwards, a lot of time has been spent debugging the log. By the way, a useful BUG monitoring tool is recommended. Fundebug.

Original: https://dev.to/duranenmanuel/...

Every time I organize my articles, I usually don't go to bed until 2 o'clock. It's very hard about 4 times a week. I hope you can give me some support and encouragement.

Communication

Ali Yun has been doing activities recently, as low as 2 fold, and is interested to see: https://promotion.aliyun.com/...

The dry goods series articles are summarized below, feel good to order Star, welcome to join the group to learn from each other.

https://github.com/qq44924588...

Due to space limitations, today's share is here only.If you want to know more, you can sweep the QR code at the bottom of each article, and then follow our WeChat public number for more information and valuable content.

Posted by jofield on Sun, 29 Sep 2019 17:08:38 -0700