Optional chaining (optional chain)

JavaScript from its inception has come a long way, offers many new features that are specifically designed to make the language more user-friendly and improve efficiency. The following are some interesting new in JavaScript I recently discovered. Some of these features have been Node, Chrome, Firefox and Safari are available, while other functions are still in proposal stage.

Optional chaining (optional chain)
Optional Optional Chaining chains use?. Operator to represent, Optional Chaining so that we can check whether there is a property of an object above. Some other languages have similar characteristics. Such as C # has Null Conditional operator. The JavaScript is Optional chaining when needed depth interviews nested object property is particularly useful.

When we access an object property before, we need to use?. Operator to determine whether the property exists.

First look at the code below:

Users = const [
{
name: "Olagunju Gbolahan",
OCCUPATION: "Software Developer",
sayName () {
the console.log (IS $ `My name} {` this.name);
},
address: {Office: "New York "}
},
{name:" Olawaseyi Moses "},
{name:" Tunde Ednut "}
];
the array object, the second object is secondUser:

const secondUser = users [1];
we need to know the user's office address, in the absence Optional chaining, we need to use a very inefficient way to verify whether the property already exists:

theAddress, secondUser.address && secondUser.address.office = const;
the console.log (theAddress,); // undefined
if we are a deeply nested objects, it must be determined by the operator && each layer the object is valid:

But with optional chaining, the code can be simplified as follows:

theAddress, secondUser .Address. Office = const;??
console.log (theAddress,); // undefined
we can also use the optional chaining to confirm the existence of an object's method:

firstUser the Users = const [0];
console.log (firstUser.sayName ()?.); // My name is Olagunju Gbolahan
If the method name does not exist, it will simply return undefined:

console.log (firstUser.sayOccupation ()?.) ; // undefined
Currently this feature has not been added to the JavaScript specification is still in draft proposal stage.

You can achieve the same functionality by babel-plugin-proposal-optional-chaining the plug.

You can also read the "Optional Chaining properties enter Stage 3, TypeScript follow" this article to learn more about the progress of this feature.

Optional catch binding (optional error capture binding)
when we know in advance what would be wrong, and we do not want redundant unused variables, this feature will send in handy.

First, look at the code block of the conventional try and catch:

{the try
const = parsedJsonData the JSON.parse (obj);
} the catch (error) {
// obj variable is not defined when using
the console.log (obj);
}
through error trapping binding, we need to provide unused variables , especially when we have to try to provide default processing blocks:

getName function () {
the let name = "Gbolahan Olagunju";
the try {
name = obj.details.name
} {} the catch
the console.log (name);
}
pipeline operator
is one of the proposed supplement JavaScript, the current is in the first phase 1. Essentially, it helps to make a plurality of function calls to read the same parameter.

It is achieved by the value of the expression is passed to the function as an argument.

Call the following function in the absence of pipeline operator case |>.

const capitalize = (input) => input[0].toUpperCase() + input.substring(1);
const removeSpaces = (input) => input.trim();
const repeat = (input) => `${input}, ${input}`;

REPEAT withoutpipe = const (capitalize (removeSpaces ( 'I AM gbols')));
the console.log (withoutpipe); // gbols the I AM, the I AM gbols
through the pipeline operator, greatly enhance readability:

withpipe = const 'I AM gbols'
|> removeSpaces
|> capitalize
|> REPEAT;
the console.log (withpipe); // // gbols the I AM, the I AM gbols
String.trimStart and String.trimEnd
these two methods before being named trimRight and trimLeft, but modified to trimStart and trimEnd name will ES2019 in, express more intuitive:

Sample code:

let message = " Welcome to LogRocket ";
message.trimStart(); // "Welcome to LogRocket "
message.trimEnd(); // "Welcome to LogRocket";
Object.fromEntries
在聊 Object.fromEntries 之前,有必要先看看 Object.entries.

Object.entries is introduced ES2017 specification for object into a array, the array may function through the relevant access.

Sample code:

devs = {const
gbols:. 5,
Andrew:. 3,
Kelani: 10,
DAFE:. 8,
};
const = arrOfDevs Object.entries (devs);
the console.log (arrOfDevs);
// [
// [ "gbols" WWW. qjljdgt.cn, 5]
// [ "Andrew", 3]
// [ "Kelani", 10]
// [ "DAFE", 8]
//]
then we can use the filter method to get an array of more than 5 years experience Object:

arrOfDevs.filter expDevs = const (www.tianyueptgw.cn ([name, yrsOfExp]) => yrsOfExp>. 5);
the console.log (expDevs);
// [
// [ "Kelani", 10]
// [ "DAFE "8]
//]
then there will be a new problem: there is no easy way back into the latest array of objects. Usually we need to write code that will become a target array:

expDevsObj {} = const;
for (the let [name, yrsOfExp] of expDevs) {
expDevsObj [name] = yrsOfExp;
}
the console.log (expDevsObj);
// {
// DAFE:. 8
// Kelani: 10
//}
but now you can put this process is greatly simplified by Object.fromEntries:

the console.log (Object.fromEntries (www.sanguoyoux.cn expDevs));
// {
// DAFE:. 8
// Kelani: 10
//}
Flat
much we need to deal with the use of deeply nested array, the array will show time Ping is particularly important.

Take a look at the following code:

const developers = [
{
name: 'Gbolahan Olagunju',
yrsOfExp: 6,
stacks: ['Javascript', 'NodeJs'www.yuanygw.com, ['ReactJs', ['ExpressJs', 'PostgresSql']]]
},
{
name: 'Daniel Show',
yrsOfExp: 2,
stacks: ['Ruby', 'Jest', ['Rails', ['JQuery', 'MySql']]]
},
{
name: 'Edafe Emunotor',
yrsOfExp: 9,
stacks: ['PHP', 'Lumen', [www.fengshen157.com'Angular', 'NgRx']]
}
];

developers.map allStacks = const ((Stacks {}) => Stacks);
the console.log (allStacks);
// [
// [ 'Javascript', 'nodejs', [' ReactJs', [ 'ExpressJs',' PostgresSQL ']]]
// [' the Ruby ',' Jest ', [' the Rails', [ 'JQuery', 'MySql']]]
// [ 'the PHP', 'Lumen', [ 'the Angular', 'NGRX' ]]
//]
allstacks variable contains deeply nested arrays in order to flatten the array, we can use Array.prototype.flat method.

Sample code:

allStacks.flat flatSingle = const ();
the console.log (flatSingle);
// [
// "the JavaScript",
// "nodejs",
// [ 'ReactJs', [' ExpressJs', www.jintianxuesha.com 'PostgresSQL ']]]
// "the Ruby",
// "Jest",
// [' the Rails', [ 'JQuery', 'MySql']]]
// "the PHP",
// "Lumen"
// [ "the Angular "," NGRX "]
//]
from the above code it can be inferred that the array is flattened with a layer depth, which is the default parameters array.prototype.flat.

We can pass a parameter to flat method to determine the extent to be flattened.

1 defaults parameter value. In order to completely flatten the array, we can deliver an infinite parameters. Parameter infinity so completely flattened array, regardless of the depth of the array.

Sample code:

allStacks.flat completelyFlat = const (Infinity);
the console.log (completelyFlat);
// [
// "the JavaScript",
// "nodejs",
// "ReactJs",
// "ExpressJs",
// "PostgresSQL",
// "Ruby",
// "Jest",
// "Rails",
// "JQuery",
// "MySql",
// "PHP",
// "Lumen",
// "Angular",
// "NGRX"
//]
flatMap
flatMap equivalent to the map method and flat methods combined, and default depth of the new method. It is equivalent to more concise code implementing logic combination of the two.

Here is a simple to use and flatMap map code:

let arr = ['my name is Gbols', ' ', 'and i am great developer'];
console.log(arr.map(word => word.split(' ')));
//[
// ["my", "name", "is"www.pingguoyul.cn , "Gbols"],
// ["", ""],
// ["and", "i", "am", "great", "developer"]
//]

the console.log (arr.flatMap (Word => word.split ( '')));
// [ "My"
// "name"
// "IS"
// "Gbols"
// ""
// ""
// "and"
// "i"
// "AM"
// "Great"
// "Developer"
//]
summed up
in this text, we detail the new features recently added some JavaScript, these new properties by reducing the lengthy code, and to enhance the readability of the code to enhance the developer experience. However, there are many new features not covered in this article, welcome to add and share.

Guess you like

Origin www.cnblogs.com/dakunqq/p/11614378.html