This is a translation of an article about some of the not-so-obvious cool features provided by the ES6 JavaScript standard. In the article, from time to time, something addictive passes, so it is quite possible that I could not translate everything quite qualitatively. If you find shoals, write me about it - correct.
{in the original there was some kind of incomprehensible gif with a monkey , which I somehow did not quite understand, and therefore I will not put it here}
Here are some ES6-based methods that are not really tricks - just using some things from the new syntax, we can pretty well cut the code, improve its readability, or perhaps just have fun. I (the author of the original, not the author of this article on Habré - note. Lane.) Plan to collect more in this article, so please feel free to add it to your bookmarks and check from time to time. Well, if you also have some funny tricks that I don’t mention here, please write about it!
Destructuring is my favorite part of ES6 syntax. Now it is in Node 6, so this case can be used on the frontend and on the server side. For more details, you can read the explanation of this case on the Mozilla site (there is also in Russian, by the way), if you do not know the basis, and for those who are MB / LF , it is possible to easily assign certain values to certain variables in nested objects.
A couple of simple examples:
// const [a, b] = [1,2]; // a = 1, b = 2 // const { a } = { a: 3 }; // a = 3 // function foo({ a }) { console.log(a); } foo({ a: 4 }); // 4
One of the chips of destructuring that you may not know about is the possibility of renaming along the way. If you used the ES6 modules, you may know how the import statement works when renaming imported objects, and you may have wondered why this is not possible with destructuring. Well, there really is just a bit of a different syntax:
// . const first = 5; const { first: second } = { first: 3 }; console.log(second); // 3 // API function verifyUser({ userId: id }) { return User.update({ id, verified: true }); }
The default parameters allow you to specify values for parameters that were not passed by the user, but what if you were going to destructurize them when they arrive? Not a problem ... We have the left side of the assignment (aka lvalue ) with the default parameters, so you can use destructuring here too!
function defaults({ a, b } = { a: 1, b: 2 }) { console.log('a', a); console.log('b', b); } defaults(); // a 1 // b 2 defaults({ a: 42, b: 32 }); // a 42 // b 32 // ! // . defaults({ a: 87 }); // a 87 // b undefined
The destructuring itself also has default parameters, so we can mix both options!
function defaults({ a = 1, b = 2 } = {}) { console.log('a', a); console.log('b', b); } defaults(); // a 1 // b 2 defaults({ a: 42, b: 32 }); // a 42 // b 32 // ? , , defaults({ a: 87 }); // a 87 // b 2
You can even destructurize a deep object or array! But intermediate object keys will not be assigned at this time. What if you want to assign some intermediate keys and some deep node? Just ask about it! In other words, as we will show in the example below, you can simply declare any variable you want (intermediate connection in this case) and use it again as a specification to go to another level (intermediate -> nested) ( this is drug addiction ... - Lane comment.
const { topLevel: { intermediate, // intermediate: { nested // } } } = { topLevel: { intermediate: { nested: 56 } } }; // intermediate is { nested: 56 } // nested is 56
Node.js is a great thing for writing scripts. For command line arguments, you can extract them from process.argv
. If you are doing something complicated, or really something for people to use, it would be better to use something like yargs for parsing. But ... if you have a script that just takes a small number of arguments, you can use array restructuring to skip the first two arguments (usually the path to Node.js and the path to the script) and assign the rest to the variables.
#!/usr/bin/env node // , node.js const [,,filepath] = process.argv; doSomethingFSLike(filepath);
The updates in the object literal syntax are really cool, and we are now zayuzayu some of the above examples using the "short names of values." The first technique is not even a trick anymore, but an opportunity to avoid tying up if you do not need it. Let's say you want to see a variable or function from the outside, but also want to use it inside functions that you export as an auxiliary object. The technique of declaring it outside the returned object and inserting it below allows you to avoid binding.
const moment = require('moment'); const PERIOD = moment.duration(3, 'days'); module.exports = { PERIOD, isWithinPeriod(test) { return moment().add(PERIOD).isAfter(test); }, }; /// , ... const timeUtils = require('./time-utils'); describe('timeUtils.isWithinPeriod', () => { it(' ', () => { const beyondPeriod = moment().add(timeUtils.PERIOD).add(timeUtils.PERIOD); assert(timeUtils.isWithinPeriod(beyondPeriod) === false); }); });
Ok, this is not ES6 of course, but you can use some features of ES6 like a short property value very conveniently with JSX.
function WhySoManyProps(props) { const user = extractUser(props); const fudge = calculateFudge(); const bits = computeBits(); // . return <SomeComponent user={user} fudge={fudge} bits={bits} />; } function Shorthand(props) { const user = extractUser(props); const fudge = calculateFudge(); const bits = computeBits(); // , , return <SomeComponent {...{ user, fudge, bits }} />; }
True, this approach is not very recommended for use in the official documentation for React.js - approx. translator.
Object.assign is a fantastic new addition that helps a lot to keep things immutable (or at least to make only ephemeral mutations to intermediate objects). But did you know that they can be set for values of arrays as well?
const original = [0,1,2,3]; const copy = Object.assign([], original, { 2: 42 }); // [0,1,42,3] console.log(original); // [ 0, 1, 2, 3 ] console.log(copy); // [ 0, 1, 42, 3 ]
Are there any other tricks you like that are missing from this article? Share them in the comments!
Source: https://habr.com/ru/post/313814/
All Articles